others-how to create a websocket server using node.js and test websocket with websocat client?

1. Purpose

In this post, I will demo how to create a websocket server quickly and test it using a websocket client.



2. Solution

2.1 Create a nodejs project

init a directory

npm init

Now we have a directory of nodejs, then we need to add websocket dependency

2.2 Add websocket library to nodejs project

Before install it, we should understand what the library is:

ws is a:

Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

now let’s install ws dependency:

npm install --save ws


2.3 Create the websocket server logic

Open and edit the app.js:

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 18080 });

wss.on('connection', function connection(ws) {
    ws.on('message', function message(data) {
        console.log('received: %s', data);
    });

    ws.send('something');
});

The above code does following:

  • Create a websocket server and listen on port 18080
  • When a client connected, send ‘something’ to the client
  • When client send message to server, print ‘received: xxxx’ on server


2.4 Start the websocket server

now the server is ready, we can start it:

node app.js

2.5 Test the websocket server with a websocket client tool

We chose the tool websocat to test the websocket server, what is websocat?

websocat is a :

Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions

Basic usage of websocat is:

$ websocat ws://ws.vi-server.org/mirror
123
123
ABC
ABC

Before using it , we need to install it:

brew install websocat


Then let’s test our websocket server using websocat as follows:

➜  kong git:(master) websocat ws://127.0.0.1:18080/
something
abc
aadsf
asdfasf
asdfasf
^C

The server echo:

➜  simple_websocket_server git:(master) ✗ node app.js   
received: abc

received: aadsf

received: asdfasf

received: asdfasf



3. Summary

In this post, I demonstrated how to create a websocket server using node.js quickly and test it with a command-line tool websocat. That’s it, thanks for your reading.