美文网首页
基于WebSocket的网上聊天室

基于WebSocket的网上聊天室

作者: 红Archer | 来源:发表于2018-01-07 21:18 被阅读0次

    思路:
    服务端:
    1、创建一个Inbound类,继承MessageInbound(client对象)
    2、重写Inbound中的on方法
    onOpen()、onClose()、onMessage()
    3、创建ClientPools(客户端池)
    1)保存所有Client对象(数据结构)
    2)添加和移除Client对象
    3)给所有Client发送消息的方法
    4、创建WebSocketServlet的子类
    重写createWebSocketInbound方法,返回第1步所创建的类
    5、用注解部署Servlet

    客户端Client:
    1、创建WebSocket对象("ws://ip:port/上下文/url")
    2、给WebSocket对象的
    onopen、onclose、onmessage(对象.data)、onerror事件捆绑函数
    3、发送按钮,调用webSocket对象的send()发送消息,离开使用close()关闭链接

    实现代码:
    客户端池ClientPools:

    public class ClientPools {
        private static Set<MyMessageInbound> clients = new HashSet<MyMessageInbound>();
        
        public static void addClient(MyMessageInbound client)
        {
            clients.add(client);
        }
        
        public static void removeClient(MyMessageInbound client)
        {
            clients.remove(client);
        }
        
        public static void sendMessage(String message)
        {
            for(MyMessageInbound client:clients)
            {
                try {
                    //给client发送消息
                    client.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    

    MessageInbound:

    public class MyMessageInbound extends MessageInbound {
    
        @Override
        protected void onClose(int status) {
            ClientPools.removeClient(this);
        }
    
        @Override
        protected void onOpen(WsOutbound outbound) {
            ClientPools.addClient(this);
            ClientPools.sendMessage("新人上线!");
            System.out.println("新人上线");
        }
    
        @Override
        protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
            // TODO Auto-generated method stub
    
        }
    
        @Override
        protected void onTextMessage(CharBuffer arg0) throws IOException {
            //有消息过来就会触发这个事件,把当前消息,推送给其他client
            System.out.println(arg0.toString());
            ClientPools.sendMessage(arg0.toString());
        }
    
    }
    

    WebSocketServlet:

    @WebServlet(urlPatterns = {"/testMsg"})
    public class MyMessageServlet extends WebSocketServlet {
    
        @Override
        protected StreamInbound createWebSocketInbound(String arg0,
                HttpServletRequest arg1) { 
            System.out.println("!!!!!!!!!!!!!");
            return new MyMessageInbound();
        }
    
    }
    

    html页面代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
    <!--
    #Layer1 {
        position:absolute;
        left:215px;
        top:27px;
        width:677px;
        height:400px;
        z-index:1;
    }
    #Layer2 {
        position:absolute;
        left:215px;
        top:441px;
        width:678px;
        height:72px;
        z-index:2;
    }
    -->
    </style>
    <script type="text/javascript">
        var webSocket = new WebSocket("ws://localhost:8080/WebSocketTalk/testMsg");
        webSocket.onopen=function(){
        }
        webSocket.onclose=function(){
        }
        webSocket.onmessage=function(msgObj){
            console.log(msgObj.data);
            document.getElementById("Layer1").innerHTML=document.getElementById("Layer1").innerHTML+"<br/>"+msgObj.data;
        }
        function toSend(){
        var _msg = document.getElementById("msg").value;
        webSocket.send(_msg);
        }
    </script>
    </head>
    
    <body>
    <div id="Layer1"></div>
    <div id="Layer2">
      <label>
      <textarea name="mes" cols="50" rows="2" id="msg"></textarea>
      <input type="submit" name="Submit" value="发送" onclick="toSend()"/>
      </label>
    </div>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:基于WebSocket的网上聊天室

          本文链接:https://www.haomeiwen.com/subject/uvimnxtx.html