Creating a WebSocket Connection
You'll learn how to establish a WebSocket connection and manage its lifecycle states.
Now that you understand what WebSockets are, let's actually create one. A WebSocket connection starts with the WebSocket constructor, which opens a persistent two-way communication channel between your browser and server.
Opening a Connection
To create a WebSocket connection, instantiate a new WebSocket object with the server URL. Use the ws:// protocol (or wss:// for secure connections, like HTTPS):
const socket = new WebSocket('ws://example.com/socket');
The connection attempt begins immediately. Think of it like making a phone call—you dial (create the WebSocket), then wait to see if someone picks up.
Connection States
WebSockets have four possible states, accessible via the readyState property:
WebSocket.CONNECTING(0): Connection is being establishedWebSocket.OPEN(1): Connection is open and ready to communicateWebSocket.CLOSING(2): Connection is closingWebSocket.CLOSED(3): Connection is closed or failed to open
Handling Connection Events
Use event listeners to respond to connection lifecycle changes:
socket.addEventListener('open', (event) => {
console.log('WebSocket connected!');
// Connection is ready to send/receive data
});
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
socket.addEventListener('close', (event) => {
console.log('WebSocket closed:', event.code, event.reason);
});
The open event fires when the connection succeeds. Until then, you cannot send messages—attempting to do so will fail.
Key Takeaway: Creating a WebSocket is as simple as new WebSocket(url), but you must listen for the open event before the connection is ready to use, and handle error and close events to manage failures gracefully.