套接字对象从何而来

时间:2019-10-28 14:36:24

标签: socket.io loopback4

我正在尝试在环回的其余应用程序中实现动态套接字路由。在下面的代码中: https://github.com/raymondfeng/loopback4-example-websocket  它接受一个套接字对象,该对象根据nsp.name将路由设置为1。它一直在聊天/ 1。此套接字对象从何而来。我想知道,而不是使其转到chats / 1,而是可以基于url使其动态。例如chat / 2。

import {Application, ApplicationConfig} from '@loopback/core';
import {HttpServer} from '@loopback/http-server';
import * as express from 'express';
import * as path from 'path';
import {WebSocketController} from './controllers';
import {WebSocketServer} from './websocket.server';

// tslint:disable:no-any

export class WebSocketDemoApplication extends Application {
  readonly httpServer: HttpServer;
  readonly wsServer: WebSocketServer;

  constructor(options: ApplicationConfig = {}) {
    super(options);

    /**
     * Create an Express app to serve the home page
     */
    const expressApp = express();
    const root = path.resolve(__dirname, '../../public');
    expressApp.use('/', express.static(root));

    // Create an http server backed by the Express app
    this.httpServer = new HttpServer(expressApp, options.websocket);

    // Create ws server from the http server
    const wsServer = new WebSocketServer(this.httpServer);
    this.bind('servers.websocket.server1').to(wsServer);
    wsServer.use((socket, next) => {
      console.log('Global middleware - socket:', socket.id);
      next();
    });
    // Add a route
   const ns = wsServer.route(WebSocketController, /^\/chats\/\d+$/);
    ns.use((socket, next) => {
      //console.log(socket)
      console.log(
        'Middleware for namespace %s - socket: %s',
        socket.nsp.name,
        socket.id,
      );
      next();
    });
    this.wsServer = wsServer;
  }

  start() {
    return this.wsServer.start();
  }

  stop() {
    return this.wsServer.stop();
  }
}

0 个答案:

没有答案