Node.js to realize websocket client

Time:2021-4-28

In my work, I make a joke about using net.socket of nodejs to connect websocket server, so I write a paper to record the information about websocket, and give the method of realizing websocket client in nodejs.

The difference between websocket and socket

  • Websocket is a two-way communication protocol, both client and server can send and receive data. Socket is not a protocol, but a set of interface between application layer and transport layer.
  • Websocket is in the application layer and is built on the TCP connection. Socket in the transport layer is used to establish a TCP connection. Socket encapsulates the complex TCP / IP protocol, which is convenient for developers to realize the function of TCP communication.

net.socket

This class is an abstraction of TCP socket or streaming IPC endpoint.See

So net.socket is a tool class in nodejs for socket communication, which has nothing to do with websocket.

About websocket

The role of websocket

Websocket is an application layer protocol based on TCP, which realizes the full duplex communication between client and server, so that both client and server can actively send data to each other. Once the websocket connection is established, the subsequent data are transmitted in the form of frame sequence on the same persistent connection, saving network bandwidth.
Websocket is suitable for the situation that the server constantly has data updates, while the client needs to get data updates in time. If only HTTP is used, in order to display the data update in real time, the client needs to send an HTTP request to get the data every short period of time to check whether it is updated. After using websocket, the server can notify the client of the updated data through websocket connection after the data is updated, so as to realize the real-time display with less overhead.

The establishment process of websocket connection

  1. The client and server establish TCP connection through three handshakes.
  2. After the TCP connection is successful, the client transmits the version number and other information supported by websocket to the server through HTTP protocol.
  3. After the server receives the handshake request, it also uses HTTP to reply to the data.
  4. After receiving the message of successful connection, the client and server communicate through TCP channel.

Implementation of websocket

Client – run in browser

Directly use the websocket object of JS to create a new websocket instance and connect it. The connection and callback setting codes are as follows:

var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function(e){
    Console.log ("connect to server successfully");
    //Send message to server
    ws.send("what`s your name?");
  }
  ws.onclose = function(e){
    Console.log ("server shutdown");
  }
  ws.onerror = function(){
    Console.log ("connection error");
  }
  //Receive messages from the server
  ws.onmessage = function(e){
    let message = "message:"+e.data+"";
    console.log(message);
  }

It should be noted that the websocket object of JS can only be accessed in the browser environment.See here

Client – not running in browser

The following methods can also implement websocket client in electron’s main process

WebSocket-Node

WebSocket-Node
The code for creating websocket connection and setting callback using websocket node is as follows:

var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket Client Connected');
    connection.send("what`s your name?");
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }

    });
    
    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

//You can't add 'echo protocol' below, otherwise you will report the error of can ` t connect due to "sec websocket protocol header". Because the server did not return the information specified in the corresponding protocol
client.connect('ws://localhost:8080/'); //, 'echo-protocol');
ws

ws
Installation:
https://github.com/websockets/ws
The code for creating websocket connection and setting callback using WS is as follows:

var ws = require("ws");
 
// url ws://127.0.0.1:6080
//Create a socket of the client, and then let the client connect to the socket of the server
var sock = new ws("ws://localhost:8080/");
sock.on("open", function () {
    console.log("connect success !!!!");
    sock.send("HelloWorld");
});
 
sock.on("error", function(err) {
    console.log("error: ", err);
});
 
sock.on("close", function() {
    console.log("close");
});
 
sock.on("message", function(data) {
    console.log(data);
});

Server

nodejs-websocket

Installation:
npm install nodejs-websocket
Create the service and set the callback function:

var ws = require("nodejs-websocket")

// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        console.log("Received "+str)
        conn.sendText(str.toUpperCase()+"!!!")
    })
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8001)
ws

Create the service and set the callback function:

const WebSocket = require('ws');

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

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

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

Websocket and socket.io

This is another area of confusion. Although both socket.io and websocket support real-time communication, they cannot be mixed.

Socket.io is not websocket, it just encapsulates websocket, polling mechanism and other real-time communication methods into a common interface, and implements the corresponding code of these real-time mechanisms on the server side. That is to say, websocket is only a subset of socket.io to realize real-time communication. Therefore, the websocket client can’t connect to the socket.io server. Of course, the socket.io client can’t connect to the websocket server.
See

Therefore, if you want to use socket.io for real-time communication, you must use socket.io-client as the client and socket.io as the server.