'JavaScript Websocket does not close on WebSocket.close()
I am using Websockets for a chat I am trying to set up. When I connect to the websocket it works fine but when I try to close the socket after two seconds and there was no connection I still get an onerror - even when closing the WebSocket with Websocket.close();
This is my function to set up the websocket:
reconnectTimeout = null;
function setupWebSocket(roomId) {
console.log('setupWebSocket: ' + roomId);
let ws_path = 'ws://192.168.2.105:8000/chat/' + chatid + '/';
console.log('Connecting to ' + ws_path);
chatSocket = new WebSocket(ws_path);
// Handle incoming messages
chatSocket.onmessage = function (socketMessage) {
// Decode the JSON
// console.log('Got websocket message.');
let data = JSON.parse(socketMessage.data);
// Handle joining (Client perspective)
if (data.join) {
console.log('Joining room ' + data.join);
}
// Handle leaving (client perspective)
if (data.leave) {
// do nothing - leave the room
console.log('Leaving room ' + data.leave);
}
if (data.msg_type == "CHATMESSAGE") {
console.log(data.message);
}
if (data.messages_payload) {
console.log(data.messages);
}
};
chatSocket.addEventListener('open', function () {
console.log('ChatSocket OPEN');
if (reconnectTimeout){
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
};
// if the websocket is really ready to receive messages
if (chatSocket.readyState == WebSocket.OPEN) {
chatSocket.send(
JSON.stringify({
command: 'join',
room: roomId,
}),
);
}
});
// If websocket get closed set chatSocket to null. Only for security purposes
chatSocket.onclose = function (e) {
console.log('ChatSocket onClose.', e.code);
// just in case the websocket didn't close like wanted
chatSocket = null;
chatSocket.close();
};
// Do nothing if the websocket opens
chatSocket.onOpen = function (e) {
console.log('ChatSocket on open', e);
};
chatSocket.onerror = function (e) {
console.log('ChatSocket on error', e);
chatSocket.close();
};
if (chatSocket.readyState == WebSocket.OPEN) {
console.log('ChatSocket OPEN');
} else if (chatSocket.readyState == WebSocket.CONNECTING) {
console.log('ChatSocket connecting..');
}
}
setUpWebsocket(3);
setTimeout(() => {
chatSocket.close();
chatSocket = null;
}, 2000)
So what I do: I am setting up the websocket and closing it after 2 seconds. When the connection can be build up it works just as I want it to, but when having e.g. no internet the socket does not close after 2 seconds as I want it to but I get this after 10 seconds:
ChatSocket on error {"isTrusted": false, "message": "failed to connect to /192.168.2.105 (port 8000) from /10.0.2.16 (port 51638) after 10000ms"}
Even After I set the chatSocket to null :/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
