连接NestJS WebSocketGateway时出现'socket hang up'错误的解决
NestJS WebSocket网关连接报错'socket hang up'的解决方法
问题场景
我按照NestJS官方文档编写了简单的WebSocket网关,相关代码如下:
网关代码
import { WebSocketGateway, SubscribeMessage, WebSocketServer, MessageBody } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway(30001) export class AppGateway { @WebSocketServer() server: Server; @SubscribeMessage('test') handleEvent(@MessageBody() data: string): string { return data; } }
App模块代码
import { Module } from '@nestjs/common'; import { AppService } from './app.service'; import { AppGateway } from './app.gateway'; @Module({ imports: [], controllers: [], providers: [AppService, AppGateway], }) export class AppModule { }
自测试main代码
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as WebSocket from 'ws'; async function bootstrap() { const app = await NestFactory.create(AppModule, { cors: true, httpsOptions: { rejectUnauthorized: false } }); await app.listen(3001); } function test() { const ws = new WebSocket('ws://localhost:30001'); ws.onopen = function () { console.log('open WebSocket'); ws.send(JSON.stringify({ event: 'test', data: { message: 'Hello world!' } })); }; ws.onmessage = function (event) { console.log('Server get messega:', event.data); }; ws.onerror = function (error) { console.log('Error WebSocket:', error); }; ws.onclose = function () { console.log('WebSocket closed'); }; } bootstrap(); test();
报错信息
运行后出现如下错误:
[Nest] 5916 - 23.09.2024, 13:38:42 LOG [NestFactory] Starting Nest application... [Nest] 5916 - 23.09.2024, 13:38:42 LOG [InstanceLoader] AppModule dependencies initialized +11ms [Nest] 5916 - 23.09.2024, 13:38:42 LOG [WebSocketsController] AppGateway subscribed to the "test" message +35ms [Nest] 5916 - 23.09.2024, 13:38:42 LOG [NestApplication] Nest application successfully started +3ms Error WebSocket: ErrorEvent { [Symbol(kTarget)]: WebSocket { _events: [Object: null prototype] { open: [Function], message: [Function], error: [Function], close: [Function] }, _eventsCount: 4, _maxListeners: undefined, _binaryType: 'nodebuffer', _closeCode: 1006, _closeFrameReceived: false, _closeFrameSent: false, _closeMessage: <Buffer >, _closeTimer: null, _extensions: {}, _paused: false, _protocol: '', _readyState: 2, _receiver: null, _sender: null, _socket: null, _bufferedAmount: 0, _isServer: false, _redirects: 0, _autoPong: true, _url: 'ws://localhost:30001/', _req: null, [Symbol(kCapture)]: false }, [Symbol(kType)]: 'error', [Symbol(kError)]: Error: socket hang up at connResetException (node:internal/errors:683:14) at Socket.socketOnEnd (node:_http_client:471:23) at Socket.emit (node:events:377:35) at endReadableNT (node:internal/streams/readable:1312:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'ECONNRESET' }, [Symbol(kMessage)]: 'socket hang up' } WebSocket closed
排查过程
尝试过更换端口、配置CORS等操作,用Postman测试也返回相同的'socket hang up'错误。即使运行NestJS官方示例,使用wscat和Postman连接时也会出现该错误。
解决方法
最终发现问题在于NestJS默认的Socket适配器是socket.io,更换为WsAdapter后问题解决。修改后的main代码如下:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { WsAdapter } from '@nestjs/platform-ws'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useWebSocketAdapter(new WsAdapter(app)); await app.listen(30001); } bootstrap();
内容的提问来源于stack exchange,提问作者Sergei Illarionov
相关产品推荐
相关产品推荐

