Browser WebSocket Unexpected Close Fix
In this tutorial, you'll learn about Browser WebSocket Unexpected Close Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Browser WebSocket connections can close unexpectedly with close codes like 1006 (abnormal closure) or 1001 (going away). These disconnections break real-time features like chat, live updates, and notifications.
The Wrong Way
const ws = new WebSocket("wss://example.com/socket");
ws.onmessage = function(event) {
console.log("Received:", event.data);
};
// No reconnect logic, no error handling
Output:
WebSocket connection to 'wss://example.com/socket' closed unexpectedly.
The Right Way
Implement automatic reconnection and handle close codes:
class ReconnectingWebSocket {
constructor(url, options = {}) {
this.url = url;
this.reconnectInterval = options.reconnectInterval || 1000;
this.maxReconnectAttempts = options.maxAttempts || 10;
this.reconnectAttempts = 0;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log("WebSocket connected");
this.reconnectAttempts = 0;
};
this.ws.onclose = (event) => {
console.log(`Closed: code=${event.code}, reason=${event.reason}`);
// Don't reconnect on intentional close (1000) or protocol error (1002)
if (event.code === 1000 || event.code === 1002) {
return;
}
if (this.reconnectAttempts < this.maxReconnectAttempts) {
const delay = this.reconnectInterval * Math.pow(2, this.reconnectAttempts);
console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1})`);
setTimeout(() => {
this.reconnectAttempts++;
this.connect();
}, delay);
}
};
this.ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
this.ws.onmessage = (event) => {
if (this.onmessage) {
this.onmessage(event);
}
};
}
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(data);
}
}
close() {
this.maxReconnectAttempts = 0;
this.ws.close(1000, "Client closing");
}
}
const ws = new ReconnectingWebSocket("wss://example.com/socket", {
reconnectInterval: 2000,
maxAttempts: 20
});
ws.onmessage = (event) => {
console.log("Message:", event.data);
};
Step-by-Step Fix
1. Log close codes for debugging
ws.onclose = (event) => {
console.log(`Close code: ${event.code}`);
console.log(`Close reason: ${event.reason}`);
console.log(`Clean close: ${event.wasClean}`);
// Common codes:
// 1000 = Normal closure
// 1001 = Going away (tab closed, navigation)
// 1006 = Abnormal closure (connection lost)
// 1009 = Message too big
};
2. Implement heartbeat keepalive
class HeartbeatWebSocket {
constructor(url) {
this.url = url;
this.pingInterval = 30000;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
this.heartbeat = setInterval(() => {
this.ws.send(JSON.stringify({type: "ping"}));
}, this.pingInterval);
};
this.ws.onclose = () => {
clearInterval(this.heartbeat);
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "pong") {
console.log("Heartbeat received");
}
};
}
}
3. Implement exponential backoff reconnection
function getReconnectDelay(attempt) {
const base = 1000;
const max = 30000;
const delay = Math.min(base * Math.pow(2, attempt), max);
return delay + Math.random() * 1000; // Add jitter
}
Prevention Tips
- Implement automatic reconnection with exponential backoff for all WebSocket connections.
- Use heartbeat/ping-pong messages to detect dead connections quickly.
- Handle all close codes explicitly and decide whether to reconnect.
- Add jitter to reconnection delays to prevent thundering herd.
- Monitor WebSocket state in a status indicator for users.
Common Mistakes with WebSocket close
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world BROWSER code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro