WebSocket Connection Failed
The WebSocket connection could not be established or was closed unexpectedly.
Explanation
WebSocket Connection Failed occurs when the client cannot establish or maintain a WebSocket connection to the server. This can happen during the initial handshake (HTTP upgrade fails), during the connection (server closes it), or during data transfer. Common causes include server not supporting WebSocket upgrade, proxy/load balancer issues, CORS restrictions, invalid WebSocket URL, authentication failures, and server-side connection limits being reached.
Common Causes
- Server doesn't support WebSocket upgrade
- Invalid WebSocket URL protocol
- Proxy/load balancer blocking upgrade
- CORS restrictions
- Authentication failure
Solution
Verify the WebSocket URL is correct (ws:// or wss:// protocol). Check that the server supports WebSocket connections and is running. Ensure proxies and load balancers are configured to forward WebSocket upgrade requests. Add event handlers for error and close events to handle failures gracefully. Implement reconnection logic with exponential backoff. Check server logs for connection rejection reasons. Verify authentication if the WebSocket endpoint requires it.
Code Example
// WebSocket connection with error handling
const ws = new WebSocket('ws://localhost:3000');
ws.on('open', () => {
console.log('Connected!');
ws.send('Hello');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error.message);
});
ws.on('close', (code, reason) => {
console.log(`Closed: ${code} ${reason}`);
});
// Reconnection with backoff
function connectWithRetry(url, retries = 5, delay = 1000) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url);
ws.on('open', () => resolve(ws));
ws.on('error', (err) => {
if (retries > 0) {
setTimeout(() => {
connectWithRetry(url, retries - 1, delay * 2)
.then(resolve).catch(reject);
}, delay);
} else {
reject(err);
}
});
});
}
connectWithRetry('ws://localhost:3000')
.then(ws => console.log('Connected'))
.catch(err => console.error('Failed:', err));
Error Information
Language
javascript
Difficulty
Intermediate
Views
230
Related Errors
JavaScript
TypeError: Cannot Read Property of Undefined
The code tries to access a property or method on an undefined or null value.
JavaScript
RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.
JavaScript
TypeError: X is not a function
The code tries to call a value as a function, but it's not a function.
Frontend
Content Security Policy Violation
The browser blocked a resource because it violated the Content Security Policy.