How To Close A Websocket Like If Chrome Window Was Closing To Flush The Buffer To 0
Solution 1:
The terminate method you are trying to use is from a server implementation of WebSocket (not browser).
If you feel worried about the close method not actually closing the connection, you can verify it by yourself.
In your browser's console, type let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");
Now in a Shell, type ping javascript.info which will give you the remote IPv6: 2606:4700:20::681a:c11.
Now type netstat -an -p tcpv6 which should display something like:
Finally, type socket.close(); in the browser's console and run netstat -an -p tcpv6 again, you'll notice that the previous row has disappeared.
Also, you'll notice that the row still shows in the browser's Network tab:
So just don't rely on it when making assumptions on the socket's status.
Solution 2:
Short version: because WebSocket object doesn't have any terminate method.
The close method (which you are calling) is enough to close the websocket. Where did you read about terminate method?
Since in your question you are speaking about "hard close" and in you code you are doing this check ws.readyState == 2 I think you are looking for something to have ws.readyState == 3.
To have this is just matter of waiting a while after you called the close method.
The onclose property could help you; try adding following lines at the end of your script
ws.onclose = function(event) {
console.log("Socket hard closed", ws.readyState);
}
Hope this helps.


Post a Comment for "How To Close A Websocket Like If Chrome Window Was Closing To Flush The Buffer To 0"