#Websocket: socket hang up

2 messages · Page 1 of 1 (latest)

umbral helm
#

Hello everyone,

I am having problems trying to connect to websocket. When I try via Postman socket.io I can connect, but when I try with wscat -c ws://localhost:8000 I get a 'socket hang up' error. I couldn't connect via React either.

Even when I made it as simple as possible the problem persists. I am leaving the codes below.

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class GatewayService
  implements OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer()
  server: Server;

  handleConnection(client: Socket) {
    console.log('Client connected:', client.id);
  }

  handleDisconnect(client: Socket) {
    console.log('Client disconnected:', client.id);
  }

  @SubscribeMessage('message')
  handleMessage(client: Socket, message: any): string {
    console.log('Received message:', message);

    client.emit('reply', 'Hello from WebSocket!');
    this.server.emit('reply', 'WebSocket started to boardcast!');
    return 'Hello from WebSocket!';
  }
}
@Module({
  providers: [GatewayService],
})
export class GatewayModule {}
@Module({
  imports: [GatewayModule],
  controllers: [],
  providers: [],
})
export class AppModule {}
async function bootstrap() {
  console.log('Websocket!');
  const app = await NestFactory.create(AppModule);
  await app.listen(CONFIG.PORT);
}
bootstrap();

[Nest] 26548 - 10/01/2024, 6:17:15 AM LOG [WebSocketsController] GatewayService subscribed to the "message" message

drifting nexus
#

Socket.io is not "plain" websocket, it's websocket with some magic on top.

In order to connect to that from react, you'll have to use the socket.io client library. When you do, you'll notice that after initial handshake it connects to a websocket at /socket.io/ path with some arguments (those are important too).