如何保持websocket活着

时间:2017-03-14 07:05:20

标签: html5 websocket java-websocket

我正在建立websocket连接,其中服务器是使用javax.websocket构建的,而客户端是在html5中。

这些代码工作正常。但经过一段时间会议结束。我想保持这个会话活着。

我有两个问题:

  1. 如果由于会话空闲时间而导致此连接关闭 出
  2. 如何让这个会话保持活力。
  3. 以下是代码:

    var wsUri="ws://localhost/";
    var websocket = new WebSocket(wsUri);
    
    var datasocket;
    var username;
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
    function join() {
        username = textField.value;
        websocket.send(username + " joined");
        console.log("joined");
    }
    
    function send_message() {
        websocket.send(username + ": " + textField.value);
    }
    
    function onOpen() {
        console.log("connected to url");
        websocket.send("Hello");
        //  writeToScreen("Connected to " + wsUri);
    }
    
    function onMessage(evt) {
    var res = {};
        console.log("onMessage: " + evt.data);
        if (evt.data.indexOf("joined") != -1) {   
        } else {
            datasocket=evt.data
            //getLatestData();
            res = JSON.parse(event.data);
            $scope.Impact = res["Impact"];
            $scope.Temperature = res["Temperature"];
            $scope.Humidity = res["Humidity"];
        }
    }
    
    function onError(evt) {
        writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    } 
    
    function writeToScreen(message) {
    //    output.innerHTML += message + "<br>";
    }
    function onClose(evt)
    {
        console.log("Disconnected");
    }
    

    以下是java代码:

    @javax.websocket.server.ServerEndpoint("/")
    public class Endpoint {
    
        private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
        static StringBuilder sb = null;
        ByteArrayOutputStream bytes = null;
    
    
        @OnMessage
        public void onMessage(Session session, String msg) {
            // provided for completeness, in out scenario clients don't send any msg.
            try {   
                // System.out.println("received msg "+msg+" from "+session.getId());
    
               sendAll(msg);  
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        private static void sendAll(String msg) {
    
            JSONParser parser = new JSONParser();
            Object obj = null ;
    
            try {
                obj = parser.parse(msg);
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            JSONObject jsonObject = (JSONObject) obj;
    
            if (sb == null) {
                sb = new StringBuilder();
            }
            sb.append(jsonObject.toString());
    
            //     System.out.println(jsonObject.toJSONString());
            try {
                /* Send the new rate to all open WebSocket sessions */  
                ArrayList<Session > closedSessions= new ArrayList<>();
                for (Session session : queue) {
                    if(!session.isOpen()) {
                         System.err.println("Closed session: "+session.getId());
                         closedSessions.add(session);
                    }
                    else {
                        session.getBasicRemote().sendText(msg);
                    }
                }
                queue.removeAll(closedSessions);
                //     System.out.println("Sending "+msg+" to "+queue.size()+" clients");
            } catch (Throwable e) {
                e.printStackTrace();
            }
    
            sb = null;
    
        }
    
        @OnOpen
        public void open(Session session) {
             queue.add(session);
             System.out.println("New session opened: "+session.getId());
        }
    
        @OnError
        public void error(Session session, Throwable t) {
            queue.remove(session);
            System.err.println("Error on session "+session.getId());  
        }
    
        @OnClose
        public void closedConnection(Session session) { 
            queue.remove(session);
            System.out.println("session closed: "+session.getId());
        }
    
    }
    

0 个答案:

没有答案