0

有人可以帮助并告诉我如何编写以下代码片段,该代码片段被编写为节点应用程序,以编写为仅具有 WebSockets 和网关类的嵌套应用程序?

    var webSocketsServerPort = 8080;
    var webSocketServer = require('websocket').server;
    var http = require('http');
    var server = http.createServer(function(request, response) {
    });
    server.listen(webSocketsServerPort, function() {
    console.log(
    new Date() + ' Server is listening on port ' + webSocketsServerPort
        );
    );
    });
    var wsServer = new webSocketServer({
    httpServer: server
    });
    wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    connection.on('message', function(data) {
    var message = JSON.parse(data.utf8Data);
    });

    connection.on('close', function(connection) {});

编辑:在 main.ts 我写了这个: app.useWebSocketAdapter(new WsAdapter(app));

这就是我的网关类的样子:

import { WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection, SubscribeMessage } from "@nestjs/websockets";
import { Server } from "websocket";
import { Logger } from "@nestjs/common";

@WebSocketGateway(8080)
export class ChatterGateway implements OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection {
    @WebSocketServer() private server: server;

    private logger: Logger = new Logger('ChatterGateway');

    afterInit(server: server) {
        this.logger.log('ChatGetway init');
    }

    handleConnection(client: any, data) {
        this.logger.log('Client connected');
    }

    handleDisconnect(client: any) {
        this.logger.log('Client disconnected');
    }

    @SubscribeMessage('request')
    handleRequest(client: any, data) {
        this.logger.log(data);
    }

    @SubscribeMessage('message')
    handleMessage(client: any, data) {
        this.logger.log(data);
    }
}
4

0 回答 0