搞定這個的過程遠比想象的困難許多。網上許多教程,一一嘗試,大多隨著庫版本的改變以及瀏覽器對協(xié)議支持的改變以失敗告終,即使成功的也語焉不詳,以下為步驟。
創(chuàng)新互聯(lián)公司專注于響水企業(yè)網站建設,響應式網站開發(fā),商城建設。響水網站建設公司,為響水等地區(qū)提供建站服務。全流程定制設計,專業(yè)設計,全程項目跟蹤,創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務
1. 運行環(huán)境
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中,F(xiàn)ile->New->Dynamic Web Project,使其如下配置
Target runtime中必須是Apache Tomcat v7.0,并且最好是引用7.0.29(可在New Runtime中配置)
注意,點擊Next->,再點擊Next->,如下圖,注意勾選Generate web.xml deployment descriptor,點擊Finish
(2) 在Java Resources下src下New->Class,如下圖
再在src下New->Class,如下圖
下面貼上上述類的代碼
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 ListsocketList = new ArrayList (); @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 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"); } // 有二進制消息數(shù)據到達,比如音頻等文件傳輸 @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); // 將字符數(shù)組包裝到緩沖區(qū)中 // 給定的字符數(shù)組將支持新緩沖區(qū);即緩沖區(qū)修改將導致數(shù)組修改,反之亦然 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,編輯為
myWebSocket index.html index.htm index.jsp default.html default.htm default.jsp echo com.trump.web.servlet.EchoServlet echo *.ws
(4) 右擊項目myWebSocket->Run As->Run on Server,如下圖,點擊Finish,
可以看到Tomacat正常運行,如下圖
(5) 在任意位置新建一個客戶端,命名為client.html,內容如下
Web Socket Demo
(6) OK!打開瀏覽器,輸入http://localhost:8080/webSocketTest/client.html
此時注意Tomcat打印出的信息,如下
3. WebSocket之所以受關注,是因為它的服務器端能主動發(fā)消息給客戶端,即MyMessageInbound中onOpen函數(shù)可以讓服務器做想做的事情。