NodeJS WebSocket множественный путь

#node.js #websocket

#node.js #websocket

Вопрос:

Привет, я пытаюсь создать класс сервера websocket с несколькими путями.

Событие подключения выдается, когда я вызываю сервер websocket с допустимым путем. Но событие сообщения никогда не выдается. Когда я использую пример кода, у меня нет проблем, но с моим классом ничего не происходит, только событие подключения. Я не понимаю, почему…

Спасибо за вашу помощь

Класс сервера WebSocket

 const http = require('http');
const WebSocket = require('ws');
const url = require('url');

class WSServer {
    #server;
    #wsServer = {};
    #ip;
    #port;
  #origin;
  #routes = {};

    constructor(ip, port, origin = null, routes = ['/']) {
        this.#ip = ip;
        this.#port = port;
        this.#origin = origin;
    this.#routes = routes;

        this.#server = http.createServer((request, response) => {
            console.log((new Date())   ' Received request for '   request.url);
            response.writeHead(404);
            response.end();
    });
    
    this.#routes.forEach(route => {
      this.#wsServer[route] = new WebSocket.Server({ noServer: true });
    })

        this.#server.listen(this.#port, this.#ip, () => {
            console.log((new Date())   ' Server is listening on port '   this.#port);
    });
    
    this.#server.on('upgrade', (request, socket, head) => {
      const pathname = url.parse(request.url).pathname;
      console.log(pathname);
      this.#routes.forEach(route => {
        if (pathname === route) {
          this.#wsServer[route].handleUpgrade(request, socket, head, (ws) => {
            this.#wsServer[route].emit('connection', ws, request);
          });
        } else {
          socket.destroy();
        }
      });
    });
  }

  clients(route = '/') {
        return this.#wsServer[route].connections;
    }

    on(route = '/', event, func) {
        this.#wsServer[route].on(event, func);
    }
}

module.exports = WSServer;
 

Пример кода

 
const WSServer = require('./WSServer');

const wsServer = new WSServer('localhost', '7070', null, ['/db', '/']);

wsServer.on('/', 'connection', function test(conn, req) {
    conn.on('message', msg => {
        console.log(msg);
    })
});

wsServer.on('/db', 'connection', function test(conn, req) {
    conn.on('message', msg => {
        console.log(msg);
    })
});
 

Ответ №1:

Проблема решена!

ошибка возникает из цикла маршрутизации в событии http-сервера onupgrade…

исправление

 if (this.#wsServer[pathname] !== undefined) {
    this.#wsServer[pathname].handleUpgrade(request, socket, head, (ws) => {
        this.#wsServer[pathname].emit('connection', ws, request);
    });
} else {
    socket.destroy();
}