When you need continuous data from a server, two approaches come to mind:
- Frequent API calls to request data (Polling)
- Utilizing WebSockets
A WebSocket is a communication protocol that enables seamless and continuous interaction between clients and servers. It offers various communication patterns, including:
- Client to Server (e.g., submitting a new post)
- Server to Client (e.g., notifying about likes/views)
- Server to Multiple Clients (e.g., broadcasting updates)
WebSocket connections maintain a persistent, bidirectional link for ongoing communication.
Unlike traditional HTTP connections, where a client sends a request and waits for a response, WebSocket connections remain open. This persistence allows continuous data exchange between clients and servers until either side decides to terminate the connection. This is akin to a publish-subscribe messaging pattern, where clients "subscribe" to updates, and servers "publish" messages to subscribers.
- Single Connection: Only one request-response is needed to establish a connection.
- Stateful Connection: WebSockets can maintain connection state, keeping track of data sent between client and server without relying on cookies or session IDs.
The WebSocket protocol serves two primary purposes:
- Opening a handshake.
- Facilitating data transfer.
To demonstrate WebSocket usage in Node.js, i've made two files: server
and client
.
The client-side HTML contains a textarea for input and a send button to communicate with the server. When the page loads, it establishes a WebSocket connection with the server.
The server-side JavaScript uses the ws module to create a WebSocket server. It handles incoming connections, manages messages, and responds conditionally to specific inputs.
// server.js
const WebSocketServer = require("ws");
const wss = new WebSocketServer.Server({ port: 8080 });
wss.on("connection", (ws) => {
// WebSocket server logic
});
- Run your WebSocket server using node main.js.
- Open client.html in a browser to interact with the WebSocket server.
- Input text, click "Send," and observe the interactions in the browser console and terminal.
WebSockets offer a powerful solution for real-time communication between clients and servers. By maintaining a persistent connection, WebSockets enable efficient data exchange, making them ideal for applications requiring continuous updates or instant notifications.
This was a basic project for me to learn and implement WebSockets