Show List

Working with WebSockets in Node.js

WebSockets are a protocol for bi-directional, real-time communication between a client and a server. They allow for full-duplex communication, meaning that data can be sent in both directions at the same time. This makes them well-suited for real-time applications such as chat applications, multiplayer games, and live data streaming.

Node.js provides the ws library, which makes it easy to work with WebSockets. Here's a simple example of a WebSocket server in Node.js:

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
  console.log('Client connected');

  socket.on('message', (message) => {
    console.log(`Received message: ${message}`);
  });

  socket.send('Welcome to the WebSocket server!');
});

In this example, a WebSocket server is created using the WebSocket.Server class. The server listens on port 8080 and logs a message to the console when a client connects. The message event is emitted when a message is received from the client, and the event listener logs the message to the console. The send method is used to send a message back to the client.

Here's a simple example of a WebSocket client in Node.js:

const WebSocket = require('ws');
const socket = new WebSocket('ws://localhost:8080');

socket.on('open', () => {
  console.log('Connected to the WebSocket server');
  socket.send('Hello from the client!');
});

socket.on('message', (message) => {
  console.log(`Received message: ${message}`);
});

In this example, a WebSocket client is created using the WebSocket class. The client connects to the WebSocket server at ws://localhost:8080 and logs a message to the console when the connection is established. The message event is emitted when a message is received from the server, and the event listener logs the message to the console. The send method is used to send a message to the server.

This is just a basic example of how you can work with WebSockets in Node.js. By utilizing the ws library, you can build powerful, real-time applications that can handle bi-directional communication between a client and a server.


    Leave a Comment


  • captcha text