Ws: Can I manually close the connection on the server after I refresh the browser?

Created on 5 Aug 2017  路  5Comments  路  Source: websockets/ws

In my project I need to manually close the websocket connection on some condition even after the user refresh the browser. But I find that when I refresh the browser the connection just closes by itself. How to keep the connection even after I refresh the browser? I have implemented ping/pong on the server. Would it be the server detects the client is not responding and closes the connection?

All 5 comments

How to keep the connection even after I refresh the browser?

You can't. The client closes the TCP connection when you refresh the page.

This is expected but it exposes a problem for me.

In my app server I will close a socket connection manually when a user hits some target. I use
if (ws && ws.readyState === WebSocket.OPEN) in a loop to test if I need to close the connection. The loop runs 10 times a second.

For example:

for (const [ws, user] of list) {
    if (userHitsTarget) {
        if (ws && ws.readyState === WebSocket.OPEN) {
            list.delete(ws);
            ws.close();
        }
    }
}

I test if the readyState equals to WebSocket.OPEN because the connection won't close instantly and the ws object still lingers on the server before it is finally removed. By doing that I don't need to close the connection or delete the socket repeatedly in my code.

But if I refresh the browser the connection is closed and the readyState is set to WebSocket.CLOSED. Now if the user still hasn't hit the target it won't trigger the above code. When the user hits the target, the socket readyState is already WebSocket.CLOSED, hence the socket won't be deleted from the list. I can move the delete logic out of the condition check, but this way the delete operation will be called multiple times a second. Is there a neat way to do this logic without doing list.delete(ws);ws.close() repeatedly?

I don't know but how about checking if readyState is WebSocket.CLOSING or WebSocket.CLOSED?

if (ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) {
  list.delete(ws);
}

Please don't open issues like this. This is a design decision in your app not a ws issue.

Thank you sorry about that but I have tried asking ws related questions on Stackoverflow.com but rarely get a good answer there. Would love to know where is the best place to ask questions related to implementing WebSocket applications using ws.

The client closes the TCP connection when you refresh the page.

Where is this information found? How do you know this? please provide a link.

Was this page helpful?
0 / 5 - 0 ratings