How do WebSockets work in Node.js?
×


How do WebSockets work in Node.js?

204

How do WebSockets Work in Node.js?

WebSockets in Node.js allow real-time, two-way communication between the server and the client over a single, long-lived TCP connection. Unlike traditional HTTP requests, which are one-directional and stateless, WebSockets keep the connection open, allowing both parties to send and receive data continuously without re-establishing the connection.

Why Use WebSockets?

If your application requires real-time updates like chat messages, notifications, live data feeds, or collaborative tools, WebSockets are the ideal choice. They offer a lightweight solution with lower latency compared to polling or long-polling HTTP techniques.

How WebSockets Work Under the Hood

WebSockets begin with an HTTP handshake. Once the connection is established, it is upgraded to a WebSocket protocol. This upgraded connection remains open, allowing the server and client to send data anytime without waiting for a request.

Setting Up a WebSocket Server in Node.js

Node.js doesn’t have built-in support for WebSockets, but you can use popular libraries like ws to get started quickly.


# Install the 'ws' library
npm install ws
  

Creating a Basic WebSocket Server


const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  console.log('Client connected');

  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
    ws.send('Message received: ' + message);
  });

  ws.send('Hello! You are connected to the WebSocket server.');
});
  

This simple example creates a WebSocket server on port 8080. It listens for new connections, handles messages from clients, and sends responses back.

Creating a WebSocket Client in the Browser


<script>
  const socket = new WebSocket('ws://localhost:8080');

  socket.onopen = function () {
    console.log('Connected to server');
    socket.send('Hello Server!');
  };

  socket.onmessage = function (event) {
    console.log('Message from server:', event.data);
  };
</script>
  

This browser-side code connects to the WebSocket server, sends a message when the connection is established, and listens for responses.

WebSocket Events You Should Know

  • open: Triggered when the connection is successfully established.
  • message: Fired when a message is received from the server.
  • close: Occurs when the connection is closed.
  • error: Captures any errors in the connection.

Real-World Use Cases for WebSockets

  • Live chat applications
  • Stock market dashboards
  • Multiplayer games
  • Collaborative editing tools (e.g., Google Docs style apps)
  • Live streaming of data (logs, analytics, etc.)

Things to Consider

- WebSockets bypass traditional HTTP layers like load balancers and proxies; make sure your server infrastructure supports them.
- They are ideal for small, frequent data transfers but may not be suitable for large payloads.
- Security considerations like using wss:// (WebSocket Secure) in production are important.

Conclusion

WebSockets in Node.js provide a robust, efficient way to build real-time, interactive applications. With libraries like ws, setting up a WebSocket server becomes straightforward, allowing seamless two-way communication between client and server. If you're building apps that require instant data updates, integrating WebSockets can greatly enhance the user experience.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat