java实现websocket

来源:互联网 发布:使用sql语句创建用户 编辑:程序博客网 时间:2024/06/06 10:45
  • websocket是什么

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

  • 前端实现

    <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

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 001416基金 基金网 基金分类 基金排行榜 封闭式基金 保险基金 基金080012 晨星基金网 如何买基金 教育基金 今日基金 基金app 基金怎么玩 鹏华基金 基金开户 诺安基金 基金申购 天宏基金 什么是基金 怎么买基金 全部基金 公基金查询 爱基金网 哪个基金好 蓝筹基金 基金377530 基金610006 基金169104 基金519091 基金163818 推荐基金 001594基金 003311基金 501066基金 基金519686 基金001553 基金519989 社保基金再度壮大 维修基金缴纳标准 基金入门与技巧 海富通股票基金 深圳社保基金管理局