Published on

Setting Up a Basic Websocket Server and Client in Nodejs

Authors

Today I had to setup a basic websocket server and communicate with it on the server side as well in NodeJS. It ended up being fairly easy. First I installed the requirements:

yarn add ws

I then configured my existing Express server to also support a web socket endpoint:

import express from 'express'
import WebSocket from 'ws'
import http from 'http'

const app = express()

const server = http.createServer(app)

// wss => web socket server
const wss = new WebSocket.Server({ server })

wss.on('connection', (ws) => {
  //this gets hit when the ws connection is first established
  ws.on('message', (message) => {
    //this is hit when the ws receives a message
    // handle message here
    const detail = JSON.parse(message)

    if (detail && detail.type === 'topic-you-expose') {
      ws.clients.forEach((client) => {
        if (client != ws && client.readyState === WebSocket.OPEN) {
          client.send(detail.payload)
        }
      })
    }
  })
})

server.listen(process.env.PORT || 3001, () => {
  console.log(
    `Server running on: [http://your-host:${server.address().port}] and [ws://your-host:${
      server.address().port
    }]`
  )
})

In the above:

  • message in websockets is always a string
    • In my case I expect that string to be a JSON object which is why I parse it
      • The object can have any structure you want in my case I gave it a topic and payload
  • The topic handler in my case checks if the message has a given topic and if it does it broadcasts the payload of that message to all clients

I have not explored it fully yet but to control specifically which clients get a topics data would require setting up session management.

The server also needs to periodically check if connections are alive and if not it needs to prune/kill them as described here.

This Nodejs package can only be used on the server side. But to create a websocket client in NodeJS that calls the server is as simple as:

import WebSocket from 'ws';

// WebSocket client => wsc
const wsc = new WebSocket('ws:localhost:3001');

...
//we need to now send a message to our server
wsc.send(messageToSend);
...

In the above messageToSend has to be a string. If you want to send a JSON object simply stringify it i.e.: wsc.send(JSON.stringify(myJsonObject));.

To test the server the excellent cli tool wscat can be used. Install it globally using npm:

npm install -g wscat

Then to use it:

  • Make sure you websocket server is running
  • Then connect to the server using: wscat -c ws://localhost:3001
    • In the above my server is running locally and on port 3001

Setting this server up and the corresponding NodeJS client ended up being very simple. The ws repo site has a bunch more examples in the README as well as in the examples folder. The code is also readable if the examples are not clear enough.