我在 nodejs 中成功运行了 websockets - 作为使用 wshttps://www.npmjs.com/package/ws 的命令行 websockets 服务器
我无法让 nestjs websockets 网关工作。我试过:https : //docs.nestjs.com/websockets/gateways - 以及 github 上的工作示例;https://github.com/nestjs/nest/tree/master/sample/02-gateways。它运行 - 但我无法连接到它。
如果我在 nodejs 中使用 ws 客户端进行连接,我会得到:
Error: socket hang up
我也试过https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en 连接。我可以用它连接到其他 websocket 服务器。
我也试过这个https://techformist.com/websockets-app-nestjs/ 它说
[Nest] 29036 - 06/11/2020, 6:42:02 pm [NestFactory] Starting Nest application...
[Nest] 29036 - 06/11/2020, 6:42:02 pm [InstanceLoader] AppModule dependencies initialized +11ms
[Nest] 29036 - 06/11/2020, 6:42:03 pm [AppGateway] Initialized
[Nest] 29036 - 06/11/2020, 6:42:03 pm [NestApplication] Nest application successfully started +3ms
Run Code Online (Sandbox Code Playgroud)
看起来它正在工作 - 但我仍然无法连接。
我究竟做错了什么?
更新:我的网关代码如下(来自https://techformist.com/websockets-app-nestjs/)
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
} from "@nestjs/websockets";
import { Logger } from "@nestjs/common";
@WebSocketGateway(3026)
export class AppGateway implements OnGatewayInit {
private logger: Logger = new Logger("AppGateway");
afterInit (server: any) {
// throw new Error('Method not implemented.'); - comment this
this.logger.log("Initialized");
}
// export class AppGateway {
@SubscribeMessage("message")
handleMessage (client: any, payload: any): string {
return "Hello world!";
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了这个问题的答案。我试图为此使用默认值,即 socket.io
我只需要适应 ws ( Nestjs 也支持)并将其用作默认值。
在 main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/platform-ws' //Add this line
async function bootstrap () {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app)) // Add this line
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2180 次 |
| 最近记录: |