WebSockets in NodeJS part 2

Welcome to Websockets in NodeJS part 2. In this part, we will be implementing the client-side and the server-side in this part, and after that WebSockets will come into action. So, without any further delay let’s jump right in.

Implementing the server

The first step is to implement the server-side javascript. Type the following code in a file named index.js.

const express = require('express')
const app = express()
const server = require('http').createServer(app);
const WebSocket = require('ws');

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

wss.on('connection', function connection(ws) {
  console.log('A new client Connected!');
  ws.send('Welcome!');

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

    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
    
  });
});

app.get('/', (req, res) => res.send('Welcome to NodeJs Tutor!'))

server.listen(3000, () => console.log(`Lisening on port :3000`))

Code Explanation:-

  • const wss = new WebSocket.Server({ server:server });  this code Is used to create a WebSocket server and we have passed a server in it because we will already have an express application up and running at this point and it will make it easy to connect to the same pot.
  •  ws.on(‘message’, function incoming(message)  gets triggered whenever server gets a message from any client. 
  •  wss.on(‘connection’, function connection(ws)  gets triggered whenever a new connection is made to the server.

Implementing the client-side:

So, we will be implementing the client-side in 2 HTML files as we want to make a chat system we will need a minimum of two clients to chat with each other. So, type the following code in a file name index.html.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Websocket1</title>
</head>
<body>
    Person 1
    <button onclick="sendMessage()">Send Message</button>
</body>
<script>
    // Create WebSocket connection.
    const socket = new WebSocket('ws://localhost:3000');

    // Connection opened
    socket.addEventListener('open', function (event) {
        console.log('Connected to WS Server')
    });

    // Listen for messages
    socket.addEventListener('message', function (event) {
        console.log('Message from server ', event.data);
    });

    const sendMessage = () => {
        socket.send('Hello From Person 1!');
    }
</script>
</html> 

And create another file named index2.html and paste the following code into it.

index2.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Websocket2</title>
</head>
<body>
    Person 2
    <button onclick="sendMessage()">Send Message</button>
</body>
<script>
    // Create WebSocket connection.
    const socket = new WebSocket('ws://localhost:3000');

    // Connection opened
    socket.addEventListener('open', function (event) {
        console.log('Connected to WS Server')
    });

    // Listen for messages
    socket.addEventListener('message', function (event) {
        console.log('Message from server ', event.data);
    });

    const sendMessage = () => {
        socket.send('Hello From Person 2!');
    }
</script>
</html>

Code Explanation:-

  •  const socket = new WebSocket(‘ws://localhost:3000’); creates a WebScoket connection.. 
  •  socket.addEventListener(‘open’, function (event) : This method opens up the connection. 
  •  socket.addEventListener(‘message’, function (event) listen for the messages. 

Websockets in NodeJS in Action

And there you have your WebSockets in NodeJS in action. You can run the code by the command npm start and make sure that both your client and server sides are running. When a client is connected to the server it will get the message that “A new client connected”. When we click on the button then it will send a “Hello” message to the server.

Output:-

So, this is it for this tutorial. We hope you liked it and found Websockets in NodeJS interesting. To keep learning NodeJS you can visit our website https://nodejstutor.com/ for more tutorials or you can also visit https://nodejs.org/en/ to read the official documentation.

Scroll to Top