91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

HTML5:WebSocket實現

發布時間:2020-07-28 02:11:49 來源:網絡 閱讀:479 作者:更深的黃 欄目:移動開發

搞定這個的過程遠比想象的困難許多。網上許多教程,一一嘗試,大多隨著庫版本的改變以及瀏覽器對協議支持的改變以失敗告終,即使成功的也語焉不詳,以下為步驟。

1. 運行環境

Java EE IDE

apache-tomcat-7.0.29(7.0.27之后才支持websocket)

IE(版本:10.0.9200.16384)

Firefox(版本:15.0)

Google Chrome(版本:23.0.1251.2)

 

2. 詳細步驟

(1) 在Java EE IDE中,File->New->Dynamic Web Project,使其如下配置

Target runtime中必須是Apache Tomcat v7.0,并且最好是引用7.0.29(可在New Runtime中配置)

HTML5:WebSocket實現

注意,點擊Next->,再點擊Next->,如下圖,注意勾選Generate web.xml deployment descriptor,點擊Finish

HTML5:WebSocket實現

(2) 在Java Resources下src下New->Class,如下圖

HTML5:WebSocket實現

再在src下New->Class,如下圖

HTML5:WebSocket實現

下面貼上上述類的代碼

 
package com.trump.web.servlet;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
public class EchoServlet extends WebSocketServlet {
private static final long serialVersionUID = -4104682919545889813L;
private Logger logger = Logger.getLogger(EchoServlet.class.getName());
private static List<MyMessageInbound> socketList = new ArrayList<MyMessageInbound>();
@Override
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {
// TODO Auto-generated method stub
logger.info("receive ws request");
return new MyMessageInbound();
}
public static synchronized List<MyMessageInbound> getSocketList() {
return socketList;
}
}
 
package com.trump.web.servlet;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.logging.Logger;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
public class MyMessageInbound extends MessageInbound {
private int userIdName = 0;
private Logger logger = Logger.getLogger(MyMessageInbound.class.getName());
public int getUserIdName() {
return userIdName;
}
protected void onOpen(WsOutbound outbound) {
super.onOpen(outbound);
userIdName = outbound.hashCode();
EchoServlet.getSocketList().add(this);
logger.info("Server onOpen");
}
protected void onClose(int status) {
EchoServlet.getSocketList().remove(this);
super.onClose(status);
logger.info("Server onClose");
}
// 有二進制消息數據到達,比如音頻等文件傳輸
@Override
protected void onBinaryMessage(ByteBuffer buffer) throws IOException {
logger.info("Binary Message Receive: " + buffer.remaining());
}
@Override
protected void onTextMessage(CharBuffer buffer) throws IOException {
String msgOriginal = buffer.toString();
int startIndex = msgOriginal.indexOf("!@#$%");
String nikeName = msgOriginal.substring(0, startIndex);
String textMsg = msgOriginal.substring(startIndex + 5);
// 將字符數組包裝到緩沖區中
// 給定的字符數組將支持新緩沖區;即緩沖區修改將導致數組修改,反之亦然
String countMsg = EchoServlet.getSocketList().size() + "人同時在線";
logger.info("Server onTextMessage: " + countMsg + nikeName + ":"
+ textMsg);
String msg1 = nikeName + ": " + textMsg;
String msg2 = "我: " + textMsg;
for (MyMessageInbound messageInbound : EchoServlet.getSocketList()) {
CharBuffer msgBuffer1 = CharBuffer.wrap(msg1);
CharBuffer msgBuffer2 = CharBuffer.wrap(msg2);
WsOutbound outbound = messageInbound.getWsOutbound();
if (messageInbound.getUserIdName() != this.getUserIdName()) {
outbound.writeTextMessage(msgBuffer1);
outbound.flush();
} else {
outbound.writeTextMessage(msgBuffer2);
}
}
}
}
(3) 打開WebContent下WEB-INF下web.xml,編輯為
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>myWebSocket</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>echo</servlet-name>
<servlet-class>com.trump.web.servlet.EchoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>echo</servlet-name>
<url-pattern>*.ws</url-pattern>
</servlet-mapping>
</web-app>
(4) 右擊項目myWebSocket->Run As->Run on Server,如下圖,點擊Finish,

HTML5:WebSocket實現

可以看到Tomacat正常運行,如下圖

HTML5:WebSocket實現

(5) 在任意位置新建一個客戶端,命名為client.html,內容如下

 
<!DOCTYPE html>
<html>
<head>
<title>Web Socket Demo</title>
<script type="text/javascript">
var ws = null;
function startServer() {
var url = "ws://127.0.0.1:8080/myWebSocket/echo.ws";
if ('WebSocket' in window) {
ws = new WebSocket(url);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(url);
} else {
alert('Your browser Unsupported WebSocket!');
return;
}
ws.onopen = function() {
document.getElementById("content").innerHTML += 'websocket open! Welcome!<br />';
};
ws.onmessage = function(event) {
document.getElementById("content").innerHTML += event.data + '<br />';
};
ws.onclose = function() {
document.getElementById("content").innerHTML += 'websocket closed! Byebye!<br />';
};
}
function sendMyMessage() {
var nickName = document.getElementById('nickName');
var textMessage = document.getElementById('textMessage');
if (ws != null && textMessage.value != '') {
ws.send(nickName.value + '!@#$%' + textMessage.value);
textMessage.value = '';
}
}
</script>
</head>
<body  type="text" id="nickName" size="20" />
<br />
<input type="text" id="textMessage" size="20" />
<input type="button"  value="Send">
<div id="content"></div>
</html>
(6) OK!打開瀏覽器,輸入http://localhost:8080/webSocketTest/client.html

HTML5:WebSocket實現

此時注意Tomcat打印出的信息,如下

HTML5:WebSocket實現

 

3. WebSocket之所以受關注,是因為它的服務器端能主動發消息給客戶端,即MyMessageInbound中onOpen函數可以讓服務器做想做的事情。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

剑阁县| 福安市| 穆棱市| 石棉县| 普兰店市| 滁州市| 双辽市| 泰州市| 彩票| 德阳市| 当涂县| 三门县| 江孜县| 西峡县| 和静县| 光山县| 仲巴县| 涿州市| 霍山县| 宜城市| 滦平县| 松原市| 兴文县| 乐东| 哈尔滨市| 漯河市| 溆浦县| 三穗县| 华坪县| 云浮市| 雅安市| 常德市| 稻城县| 黄石市| 恩施市| 济源市| 海安县| 安西县| 海晏县| 那坡县| 寻乌县|