美文网首页碎片
websocket(超简易群聊)

websocket(超简易群聊)

作者: kafeimao | 来源:发表于2020-02-19 18:49 被阅读0次

    依赖

    <dependencies>
            <dependency>
                <groupId>org.java-websocket</groupId>
                <artifactId>Java-WebSocket</artifactId>
                <version>1.3.0</version>
            </dependency>
        </dependencies>
    

    服务端

    import org.java_websocket.WebSocket;
    import org.java_websocket.handshake.ClientHandshake;
    import org.java_websocket.server.WebSocketServer;
    
    import java.net.InetSocketAddress;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @Author shiyangfan
     * @Date 2020-02-19
     **/
    public class ServerDemo extends WebSocketServer {
        private List<WebSocket> webSocketList = new ArrayList<WebSocket>();
        private Map<WebSocket,String> webSocketStringMap = new HashMap<WebSocket, String>();
    
        public ServerDemo() throws UnknownHostException {
        }
        public ServerDemo(int port) throws UnknownHostException {
            super(new InetSocketAddress(port));
            System.out.println("websocket服务端启动:"+port);
        }
        /**
         * 触发连接事件
         */
        @Override
        public void onOpen(WebSocket conn, ClientHandshake clientHandshake) {
            System.out.println("new connection :" + conn.getRemoteSocketAddress().getAddress().getHostAddress());
            webSocketList.add(conn);
        }
        /**
         * 连接断开时触发关闭事件
         */
        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            webSocketList.remove(conn);
            for (WebSocket web:webSocketList) {
                web.send(webSocketStringMap.get(conn)+"离开了聊天室");
                webSocketStringMap.remove(conn);
            }
        }
        /**
         * 客户端发送消息到服务器时触发事件
         */
        @Override
        public void onMessage(WebSocket conn, String message) {
            if(message.contains("%nick%")){
                String nickname = message.replace("%nick%","");
                webSocketStringMap.put(conn,nickname);
                //向所有客户端发送消息
                for (WebSocket web:webSocketList) {
                    web.send(nickname+" 进入了聊天室");
                }
            }else{
                for (WebSocket web:webSocketList) {
                    web.send(webSocketStringMap.get(conn)+": "+message);
                }
            }
        }
        /**
         * 触发异常事件
         */
        @Override
        public void onError(WebSocket conn, Exception e) { }
        /**
         * 启动服务端
         * @param args
         * @throws UnknownHostException
         */
        public static void main(String[] args) throws UnknownHostException {
            new ServerDemo(9999).start();
        }
    }
    
    
    
    

    客户端

    <!DOCTYPE HTML>
    <html>
    <head>
      <meta charset="utf-8">
      <title>websocket 客户端</title>
      <style>
        ul{
          overflow: scroll;
          width: 400px;
          height: 200px;
          padding-left: 5px;
        }
        li{
          list-style: none;
        }
      </style>
    </head>
    <body>
      <ul id="rev_info"></ul>
      <input id="send_info" type="text" placeholder="输入发送的内容,回车">
      <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
      <script type="text/javascript">
        var nickname = ""
        function getNickname(){
          nickname = prompt("请输入你的昵称:");
          while(!nickname || nickname.trim()==""){
            nickname = prompt("请输入你的昵称:");
          }
        }
        //进入聊天室,必须有个名字
        getNickname();
        // 创建一个 websocket
        var ws = new WebSocket("ws://localhost:9999");
        //连接成功触发
        ws.onopen = function () { 
           ws.send("%nick%"+nickname)
        };
        //接收到消息触发
        ws.onmessage = function (evt) {
          $("#rev_info").append("<li>" + evt.data + "</li>")
        };
        //关闭连接触发
        ws.onclose = function () { alert("连接已关闭..."); };
        $("body").bind("keypress", function (e) {
          if ((e.keyCode || e.which) == 13) {
            ws.send($("#send_info").val())
            $("#send_info").val("")
          }
        })
      </script>
    </body>
    </html>
    

    效果


    image.png

    相关文章

      网友评论

        本文标题:websocket(超简易群聊)

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