SoFunction
Updated on 2025-03-10

Example of a simple method to use Websocket connection in koa

Preface

At a project requirements meeting, there is a new requirement that users actively send data from the management backend to the app frontend, so that the frontend can make some user interaction with the actively sent data. The implementation idea is very clear, using Websocket.
Websocket is a natural full-duplex, bidirectional, single-socket connection built on the TCP protocol. Compared with the HTTP protocol, once a Websocket link is established, it can conduct two-way real-time communication;

ws module installation

Since the background is developed based on node+koa2+mongo. For pure node projects, there are many websocket middleware based on node, and the first thing I want to use is koa-websocket. This middleware is very simple to use, this is the official website (it's very simple to check it out if you have time./package/koa-websocket)。

But in the end, the project gave up using koa-websocket, because this middleware has been maintained for a long time and it is difficult to solve the subsequent problems. Second, this requires re-listening to the new port. If it is just for a function, it is a bit wasteful. Finally I chose the ws module.ws document address

After all, the most widely used WebSocket module is ws.

First install the ws module

npm install ws --save

websocket initialization

Step 1: Introducing WS module

const WebSocket = require('ws')

Step 2: You need to create a WS service module and mount it on the existing server server. The purpose is to use the same port as the original server. The path is to specify the request path of this websocket to avoid invalid connections.

class ws {
    static online = 0 // Online connection    static ws =  //Default instance    static init(server) {
        // Create an instance         = new ({ server,path: '/**/**/websockets'}); 
    } 
    // Send client data    static sendToCliect(Data) {}
}
 = ws

Step 3: Connection processing. In the connection between websocket and customer, we need to handle various situations to determine whether to close the disconnection. In the connection event callback function, we can receive the current connection ws instance and the current request information request. This facilitates us to perform current connection processing

static init(server) {
    // Create an instance     = new ({ server,path: '/**/**/websockets'}); 
    ('connection', async (ws, request) => {
        if(!(('/**/**/websockets'))){
            return ();
        }
         = ._server._connections;
        (`socketCurrently online${}Connections`)
        const {
            query: { id }
        } = ();
        if (!id) {
            return ();
        } 
        try {
           //do something
           // Here you can do some behaviors such as strengthening judgment and querying databases
             = id // Add a unique identifier for the ws instance            const obj = {"message":"Connected successfully","retCode": 200}
            ((obj))
        } catch (error) {
            ('websocket connection error',error)
            return ();
        }
    });
}  

Step 4: Mount it in the project server, the startup file of the koa project is basically in the bin/www file

const app = require('../app')
const http = require('http');
const WS = require('../wss/websocket')
/**
 * Create HTTP server.
 */
const server = (());

/**
 * Create Socket server.
 */
 
 (server)
 
 /**
 * Listen on provided port, on all network interfaces.
 */

(9000,'0.0.0.0');

Websocket sends data

To actively send data, you need to find the corresponding requester and return the data accurately to the corresponding receiver. At this time, you use the unique instance identifier added in the connection. Now create a function that sends data.

class ws {
    
    // Send client data    static sendToCliect(Data) {
        let iskeep = false // Add a variable to make a successful judgment        if (!( instanceof )) {
            return iskeep;
        }
        const {id } = Data
        ((client) => {
            if ( ===  &&  === id) { 
                // Send to the specified matching id                ((Data));
                iskeep = true
            }
        });
        return iskeep; 
    }
}

use

const WS = require('../wss/websocket')
// do something 
const data ={}
const send =  (data) // Issuing dataif(send){
    return 'success' 
}

return 'Dispatch failed, connection instance disconnected or exception'

Summarize

Using websocket is simple in the client

const ws = new WebSocket(`ws://***.***.***/websocket`)
 = () => {
    ('WebSocket onopen')
}
 = e => {
    //Receive the message and process it}

Note: The WS service is a service that is executed independently of Koa. Although they share a port, they will not pass through Koa middleware. Therefore, some authentication of Koa middleware will be invalid and need to be independently judged in the WS service.
The above is the simple use of WS module in the koa project for websocket development.

This is the article about the example of the simple method of using Websocket connection in koa. For more related content on koa, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!