Sometimes, we want to reconnect to WebSocket after close connection with JavaScript.
In this article, we’ll look at how to reconnect to WebSocket after close connection with JavaScript.
How to reconnect to WebSocket after close connection with JavaScript?
To reconnect to WebSocket after close connection with JavaScript, we create a new WebSocket
object when the connection is closed.
For instance, we write
const startWebsocket = () => {
let ws = new WebSocket("ws://localhost:8080");
ws.onmessage = (e) => {
console.log("websocket message event:", e);
};
ws.onclose = () => {
ws = null;
setTimeout(startWebsocket, 5000);
};
};
startWebsocket();
to define the startWebsocket
function.
In it, we create a new WebSocket
object to start the connection.
Then we set its onclose
property to a function that calls startWebsocket
to restart the connection.
Conclusion
To reconnect to WebSocket after close connection with JavaScript, we create a new WebSocket
object when the connection is closed.