How to Create a WebSockets Server Using Node.js

Posted by

WebSockets is a communication protocol that provides full-duplex communication channels over a single TCP connection. It allows a client and a server to establish a persistent connection and exchange real-time data. In this tutorial, we will learn how to set up a WebSockets server in Node.js.

Step 1: Create a new Node.js project
First, let’s create a new Node.js project. Open your terminal and run the following command:

mkdir websocket-server
cd websocket-server
npm init -y

This will create a new directory called websocket-server and initialize a new Node.js project.

Step 2: Install the ws module
Next, we need to install the ws module, which is a popular Node.js WebSocket library. Run the following command in your terminal:

npm install ws

Step 3: Create a WebSocket server
Now, let’s create a new file called server.js in the websocket-server directory and write the following code to set up a WebSocket server:

const WebSocket = require('ws');

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

wss.on('connection', function connection(ws) {
  console.log('A new client has connected');

  ws.on('message', function incoming(message) {
    console.log('Received: %s', message);

    // Echo the message back to the client
    ws.send(`You sent: ${message}`);
  });

  ws.on('close', function close() {
    console.log('A client has disconnected');
  });
});

This code creates a new WebSocket server using the ws module and listens on port 8080. It logs a message when a new client connects and echoes back any messages received from the client.

Step 4: Start the WebSocket server
Finally, let’s start the WebSocket server by running the following command in your terminal:

node server.js

This will start the WebSocket server and listen for incoming connections on port 8080.

Step 5: Test the WebSocket server
To test the WebSocket server, you can use a WebSocket client like wscat or a browser-based WebSocket client. Here is an example of how you can connect to the WebSocket server using wscat:

wscat -c ws://localhost:8080

You can then send messages to the server and see the responses. For example, you can send a message like Hello, WebSocket server! and receive the echo back response.

Congratulations! You have successfully set up a WebSocket server in Node.js. You can now build real-time applications that require bi-directional communication between clients and servers using WebSockets.

0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@gyros9162
2 months ago

Such a simple and useful tutorial! Thanks !

@AbdelilahEnglish
2 months ago

Thank you so much ❤❤

@user-kb7cp3hi4h
2 months ago

how to host cloud ?

@user-hr7mq6yt4x
2 months ago

thank

@eyalharush5218
2 months ago

link is broken [=