簡體   English   中英

如何讓 websocket 活着

[英]How to keep websocket alive

我正在建立 websocket 連接,其中服務器使用javax.websocket ,客戶端位於 JavaScript。

這些代碼工作正常。 但一段時間后 session 正在關閉。 我想讓這個 session 活着。

我有兩個問題:

  1. 如果此連接由於 session 空閑超時而關閉
  2. 如何讓這個 session 活着。

以下是 JavaScript 代碼:

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());
    }
    
}

您可以使用 IdleTimout 中的負數禁用服務器中的超時

session.setMaxIdleTimeout(-1)

如果 session 處於非活動狀態,則設置容器關閉之前的非零毫秒數,即沒有發送或接收消息。 值為 0 或負值表示 session 永遠不會因不活動而超時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM