java实现websocket

  • websocket是什么

    websocket是一种基于TCP的网络协议,实现了浏览器与服务器的全双工的通信方式。协议包括一个开放的握手以及随后TCP层上的消息帧。

  • 环境需要
    Tomcat7以上,需要jar包:tomcat-websocket.jar和websocket-api.jar

  • 前端实现

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        <div id="info">
            <button onClick="connect()">打开连接</button>
            <button onClick="closeWebSocket()">关闭连接</button>
        </div>
    
    <script src="js/jquery.min.js"></script>
    <script>
    
        var websocket = null;
    
        var result;
    
    
         //判断当前浏览器是否支持WebSocket
         function connect(){
             //websocket当前状态,0未连接,1已连接,2正在关闭连接,3连接已关闭或不可用
             var websocketState = websocket?(websocket.readyState?websocket.readyState:0):0;
             //如果当前已连接,则不再建立新的连接
             if(websocketState !== 1){
                 if ('WebSocket' in window) {
                    var url = '';
                    if (window.location.protocol == 'http:') {
                        url = 'ws://localhost:8080/mssm/websocket';
                    } else {
                        url = 'wss://localhost:8080/mssm/websocket';
                    }
                    websocket = new WebSocket(url);
                   }
                   else {
                       console.log('当前浏览器 Not support websocket')
                   }
    
                    //连接发生错误的回调方法
                     websocket.onerror = function () {
                         console.log("WebSocket连接发生错误,重新连接。。");
                         connect();
                     };
    
                     //连接成功建立的回调方法
                     websocket.onopen = function () {
                        heartConnect.start();
                        console.log("WebSocket连接成功");
                     }
    
                     //接收到消息的回调方法
                     websocket.onmessage = function (event) {
                      result = event.data;
                         console.log("接受回的消息"+event.data);
                     }
    
                     //连接关闭的回调方法
                     websocket.onclose = function () {
                         console.log("WebSocket连接关闭");
                     }
             }else{
                 console.log('当前已经连接websocket,不会重复连接');
             }
    
         }
         connect();
    
    
         //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
          window.onbeforeunload = function () {
              closeWebSocket();
          }
    
         //关闭WebSocket连接
          function closeWebSocket() {
              heartConnect.close();
              websocket.close();
          }
    
          //发送消息
          function send() {
              var message = "this is a message from client";
              websocket.send(message);
          }
    
          var heartConnect = {
                 timeOut:6000,
                 timeOutObj:null,
                 start:function(){
                     this.timeOutObj = setTimeout(function(){
                         var websocketState = websocket?(websocket.readyState?websocket.readyState:0):0;
                         if(websocketState===1){
                             console.log('websocket连接正常,重置心跳');
                             clearTimeout(this.timeOutObj);
                             heartConnect.start();
                         }else{
                             console.log('websocket连接失败,重新连接。。');
                             connect();
                         }
                     },this.timeOut);
                 },
                 close:function(){
                     clearTimeout(this.timeOutObj);
                 }           
          }
    
    
    </script>
    </body>
    </html>
    
  • java实现

    @ServerEndpoint("/websocket")
    public class WebSocketController {
        //静态变量,用来记录当前在线连接数。线程安全。
        private static AtomicInteger onlineCount = new AtomicInteger(0);
    
        //concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象
        private static ConcurrentHashMap<String,WebSocketController> webSocketMap = new ConcurrentHashMap<String, WebSocketController>();
        //与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
    
        /**
         * 连接建立成功调用的方法
         * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
         */
        @OnOpen
        public void onOpen(Session session){
            this.session = session;
            webSocketMap.put(session.getId(), this);
            addOnlineCount();           //在线数加1
            System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        }
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose(){
            webSocketMap.remove(this.session.getId());
            subOnlineCount();           //在线数减1
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    
        /**
         * 收到客户端消息后调用的方法
         * @param message 客户端发送过来的消息
         * @param session 可选的参数
         */
        @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("来自客户端的消息:" + message);
            //群发消息
            for(String key:webSocketMap.keySet()){
                try{
                    webSocketMap.get(key).sendMessage("你的id为:"+key);
                }catch(IOException e){
                    e.printStackTrace();
                    continue;
                }
            }
        }
    
        /**
         * 发生错误时调用
         * @param session
         * @param error
         */
        @OnError
        public void onError(Session session, Throwable error){
            System.out.println("发生错误");
            error.printStackTrace();
        }
    
        /**
         * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
         * @param message
         * @throws IOException
         */
        public void sendMessage(String message) throws IOException{
            this.session.getBasicRemote().sendText(message);
            //this.session.getAsyncRemote().sendText(message);
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount.get();
        }
    
        public static synchronized void addOnlineCount() {
            //将原子变量+1
            WebSocketController.onlineCount.getAndIncrement();
        }
    
        public static synchronized void subOnlineCount() {
            WebSocketController.onlineCount.getAndDecrement();
        }
    }
    
  • 项目地址:https://github.com/Xchunguang/xuchg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值