WebSocket實現簡單的web聊天室,websocketweb聊天室

來源:互聯網
上載者:User

WebSocket實現簡單的web聊天室,websocketweb聊天室
1.需要Tomcat7.0所以伺服器2.需要JDK7.03.手工加入Tomcat7.0中lib目錄下的一下三個包catalina.jar、tomcat-coyote.jar、websocket-api.jar4.項目部署後,請將伺服器中當前項目下的catalina.jar、tomcat-coyote.jar、websocket-api.jar三個包刪除。5.項目目錄結構如下



Servlet代碼
package com.yc.websockets;
import java.io.IOException;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.util.ArrayList;import java.util.List;
import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.websocket.MessageInbound;import org.apache.catalina.websocket.StreamInbound;import org.apache.catalina.websocket.WebSocketServlet;import org.apache.catalina.websocket.WsOutbound;
@SuppressWarnings({"deprecation","unused", "serial"})public class WebSocketTest extends WebSocketServlet {private static List<MyMessageInbound> userList = new ArrayList<MyMessageInbound>();private HttpSession session;
    @Override    protected StreamInbound createWebSocketInbound(String str, HttpServletRequest request) {    session=request.getSession();        return new MyMessageInbound();    }
    private class MyMessageInbound extends MessageInbound {        WsOutbound myoutbound;
        /**         * 當使用者登入時,WebSocket握手完成,建立完畢,WsOutbound用於向用戶端發送資料         */public void onOpen(WsOutbound outbound) {            try {                System.out.println("Open Client.");                this.myoutbound = outbound;                userList.add(this); //添加目前使用者                                //向客服端發送資訊                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));            } catch (IOException e) {                e.printStackTrace();            }        }
/** * 使用者退出時,WebSocket關閉事件,參數status應該來自org.apache.catalina.websocket.Constants * 中定義的幾個常量,可以參考文檔或者核對一下Tomcat的源碼 */        @Override        public void onClose(int status) {            userList.remove(this); //移除目前使用者        }
       /**        * 接受使用者發過來的資訊,有簡訊資料到達        */        @Override        public void onTextMessage(CharBuffer cb) throws IOException {            for (MyMessageInbound mmib:userList){ //迴圈向所有線上使用者發送目前使用者的資訊                CharBuffer buffer = CharBuffer.wrap(cb);                mmib.myoutbound.writeTextMessage(buffer); //調用指定使用者的發送方法發送目前使用者資訊                mmib.myoutbound.flush(); //清空緩衝            }        }
        /**         * 有二進位訊息資料到達,暫時沒研究出這個函數什麼情況下觸發,js的WebSocket按理說應該只能send文本資訊才對         */        @Override        public void onBinaryMessage(ByteBuffer bb) throws IOException {        }    }}

web.xml設定檔
 <?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee ;http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><display-name></display-name>  <servlet><servlet-name>webServlet</servlet-name><servlet-class>com.yc.websockets.WebSocketTest</servlet-class></servlet><servlet-mapping><servlet-name>webServlet</servlet-name><url-pattern>/webServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.html</welcome-file></welcome-file-list></web-app>
index.html
<!DOCTYPE html><html><head><meta charset=UTF-8><title>Tomcat WebSocket Chat</title><script>//設定WebSocket,注意協議是ws,請求是指向對應的WebSocketServlet的/*設定WebSocket,注意協議是ws,請求是指向對應的WebSocketServlet的var url = "ws://127.0.0.1:8080/j2ee6/echo.ws";// 建立WebSocket執行個體,下面那個MozWebSocket是Firefox的實現if ('WebSocket' in window) {ws = new WebSocket(url);} else if ('MozWebSocket' in window) {ws = new MozWebSocket(url);} else {alert('Unsupported.');return;}*/var ws = new WebSocket("ws://218.196.14.208:8080/webSocket/webServlet");
//WebSocket握手完成,串連成功的回調//有個疑問,按理說new WebSocket的時候就會開始串連了,如果在設定onopen以前串連成功,是否還會觸發這個回調ws.onopen = function() {//請求成功};
//收到伺服器發送的簡訊, event.data表示常值內容ws.onmessage = function(message) {document.getElementById("talkInfo").innerHTML+=message.data+"<hr style='border: 1px dashed #CCC'/>";};
//關閉WebSocket的回調ws.onclose = function() {//alert('Closed!');};
// 通過WebSocket想向伺服器發送一個文本資訊function postToServer() {ws.send(document.getElementById("content").value);document.getElementById("content").value = "";}
//關閉WebSocketfunction closeConnect() {ws.close();}</script><style>* {margin: 0 auto;padding: 0px;font-size: 12px;font-family: "微軟雅黑";line-height: 26px;}
#bigbox {margin:0px auto;padding:0px;width:70%;}
#talkInfo{width:100%;height:500px;border:1px solid red;overflow: scorll;}
#operation{width:100%;height:30px;margin-top:10px;}
#content{height:30px;line-height:30px;}</style></head><body><div id="bigbox"><div id="talkInfo"></div><div id="operation"><center><input type="text" name="content" id="content" size="100"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value=" &nbsp;發送&nbsp; " onclick="postToServer()" />&nbsp;&nbsp;<input type="button" value=" &nbsp;我閃 &nbsp; " onclick="closeConnect()" /></center></div></div></body></html> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.