WebSockets provide a full-duplex communication channel over a single TCP connection.
They allow real-time data exchange between a client and a server, making them ideal for live applications like chat systems, gaming, real-time notifications, and stock price updates.
In this tutorial, you’ll learn:
- What WebSockets are.
- How WebSocket connections work.
- Using WebSockets in HTML5 with examples.
- Practical applications of WebSockets.
1. What is WebSocket?
WebSocket is a communication protocol designed for real-time, bidirectional communication:
- Persistent Connection: Once established, the connection remains open for continuous data transfer.
- Low Latency: Reduces the overhead of HTTP requests and responses.
- Event-Driven: Messages can be sent and received as events.
2. How WebSocket Works
- Handshake: The client initiates a connection by sending a WebSocket handshake request.
- Connection Established: The server responds, and a persistent WebSocket connection is established.
- Message Exchange: Both the client and server can send messages at any time.
3. Creating a WebSocket Server
Before using WebSockets in HTML, you need a WebSocket server. Here’s an example using Node.js:
Node.js WebSocket Server
// Install the `ws` library: npm install ws const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); console.log('WebSocket server is running on ws://localhost:8080'); wss.on('connection', (ws) => { console.log('New client connected'); // Send a message to the client ws.send('Welcome to the WebSocket server!'); // Listen for messages from the client ws.on('message', (message) => { console.log(`Received: ${message}`); ws.send(`Server received: ${message}`); }); // Handle client disconnection ws.on('close', () => { console.log('Client disconnected'); }); });
4. Connecting to a WebSocket in HTML5
Example 1: Establishing a WebSocket Connection
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Connection</title> </head> <body> <h1>WebSocket Example</h1> <p id="status">Connecting...</p> <script> // Create a WebSocket connection const ws = new WebSocket('ws://localhost:8080'); // Handle connection open ws.onopen = () => { document.getElementById('status').textContent = 'Connected to WebSocket server!'; console.log('Connection opened'); }; // Handle messages from the server ws.onmessage = (event) => { console.log('Message from server:', event.data); }; // Handle connection close ws.onclose = () => { document.getElementById('status').textContent = 'Disconnected from WebSocket server.'; console.log('Connection closed'); }; // Handle connection errors ws.onerror = (error) => { console.error('WebSocket error:', error); }; </script> </body> </html>
Explanation:
- new WebSocket(url): Creates a connection to the WebSocket server.
- Event Handlers:
- onopen: Triggered when the connection is established.
- onmessage: Triggered when a message is received from the server.
- onclose: Triggered when the connection is closed.
- onerror: Triggered on connection errors.
5. Sending Messages to the Server
Example 2: Sending Messages
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Send Messages</title> </head> <body> <h1>WebSocket Chat</h1> <p id="status">Connecting...</p> <input type="text" id="messageInput" placeholder="Type your message"> <button id="sendMessage">Send</button> <p id="messages"></p> <script> const ws = new WebSocket('ws://localhost:8080'); const messageInput = document.getElementById('messageInput'); const messages = document.getElementById('messages'); // Update status when connected ws.onopen = () => { document.getElementById('status').textContent = 'Connected to WebSocket server!'; }; // Display messages from the server ws.onmessage = (event) => { const p = document.createElement('p'); p.textContent = `Server: ${event.data}`; messages.appendChild(p); }; // Send a message when the button is clicked document.getElementById('sendMessage').onclick = () => { const message = messageInput.value; if (message) { ws.send(message); const p = document.createElement('p'); p.textContent = `You: ${message}`; messages.appendChild(p); messageInput.value = ''; } }; </script> </body> </html>
Explanation:
- ws.send(message): Sends data to the server.
- Messages from the server are displayed in a <p> tag dynamically added to the page.
6. Closing the WebSocket Connection
You can close the WebSocket connection using the close method.
Example 3: Closing the Connection
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Close Connection</title> </head> <body> <h1>WebSocket Close Example</h1> <button id="closeConnection">Close Connection</button> <p id="status">Connecting...</p> <script> const ws = new WebSocket('ws://localhost:8080'); ws.onopen = () => { document.getElementById('status').textContent = 'Connected to WebSocket server!'; }; ws.onclose = () => { document.getElementById('status').textContent = 'Connection closed.'; }; document.getElementById('closeConnection').onclick = () => { ws.close(); }; </script> </body> </html>
Explanation:
- ws.close(): Closes the WebSocket connection.
7. Practical Applications of WebSockets
Real-Time Chat Application
Combine all the above examples to create a real-time chat application where multiple clients can communicate through a WebSocket server.
8. WebSocket Events Summary
Event | Description |
---|---|
onopen | Fired when the WebSocket connection is established. |
onmessage | Fired when a message is received from the server. |
onclose | Fired when the WebSocket connection is closed. |
onerror | Fired when there is an error in the connection. |
9. Best Practices
- Graceful Degradation: Use fallback mechanisms (e.g., HTTP polling) for browsers that do not support WebSockets.
- Connection Management: Handle reconnections in case of dropped connections.
- Security: Use secure WebSockets (wss://) for encrypted communication.
- Error Handling: Implement robust error handling for a seamless user experience.
10. Conclusion
In this tutorial, you learned:
- How to create a WebSocket server with Node.js.
- How to establish a WebSocket connection in HTML5.
- Sending and receiving messages with WebSockets.
- Closing WebSocket connections gracefully.
- Practical applications and best practices.
WebSockets are a powerful tool for building real-time, event-driven applications. Experiment with the examples above to implement WebSockets in your projects