There are several methods to implement WebSocket reconnection in web applications. Below are two common approaches.
Method One: Using a Third-Party Library
A popular choice is the ReconnectingWebSocket library. It simplifies the process of handling WebSocket reconnections.
var ws = new WebSocket('ws://example.com/socket');
// Replace with
var ws = new ReconnectingWebSocket('ws://example.com/socket');
Method Two: Custom Implementation with setTimeout
Alternatively, you can manually manage reconnections using JavaScript's setTimeout.
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Example</title>
</head>
<body>
Sender ID: <input id="senderId" value="2">
Receiver ID: <input id="receiverId" value="3">
<button onclick="initConnection()">Connect</button>
<button onclick="closeConnection()">Disconnect</button><br>
Message: <input id="msgInput" value="Hello">
<button onclick="sendMessage()">Send</button>
<div id="chatLog"></div>
<script>
let socket;
let reconnectTimer;
const maxRetries = 100;
let retryCount = 0;
function initConnection() {
const senderId = document.getElementById('senderId').value;
const url = `ws://${window.location.host}/ws/${senderId}`;
socket = new WebSocket(url);
socket.onopen = handleOpen;
socket.onmessage = handleMessage;
socket.onclose = handleClose;
socket.onerror = handleError;
}
function closeConnection() {
socket.close();
}
function sendMessage() {
const senderId = document.getElementById('senderId').value;
const receiverId = document.getElementById('receiverId').value;
const message = document.getElementById('msgInput').value;
const payload = JSON.stringify({ senderId, receiverId, message });
socket.send(payload);
appendToChat(`${senderId}: ${message}`);
}
function handleOpen() {
console.log('Connection opened.');
}
function handleMessage(event) {
if (!event.data) return;
const receiverId = document.getElementById('receiverId').value;
appendToChat(`${receiverId}: ${event.data}`);
}
function handleClose() {
console.log('Connection closed.');
retryConnection();
}
function handleError() {
console.error('WebSocket error.');
retryConnection();
}
function retryConnection() {
retryCount++;
console.log(`Retry attempt ${retryCount}...`);
if (retryCount >= maxRetries || socket.readyState === WebSocket.OPEN) {
clearTimeout(reconnectTimer);
} else if (socket.readyState === WebSocket.CLOSED) {
initConnection();
} else {
reconnectTimer = setTimeout(retryConnection, 100);
}
}
function appendToChat(message) {
const chatLog = document.getElementById('chatLog');
chatLog.innerHTML += `<br></br>${message}`;
}
</script>
</body>
</html>
The key part of this implementation is calling the retryConnection function when the WebSocket closes. This funcsion checks the connection state and retries connecting if necessary, respecting the maximum number of retries.