fastify / fastify-websocket

basic websocket support for fastify
MIT License
394 stars 72 forks source link

Cannot connect to WebSocket server #263

Closed TimonVS closed 1 year ago

TimonVS commented 1 year ago

Prerequisites

Fastify version

4.20.0

Plugin version

8.2.0

Node.js version

18.17.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13.4

Description

I have tried in many different environments (Replit, Stackblitz, locally, with and without ESM enabled), but I just cannot seem to be able to connect with a WS server created with this plugin. Network time in DevTools is stuck on "Pending".

Steps to Reproduce

I copied the example from the docs for the server:

const fastify = require('fastify')();

fastify.register(require('@fastify/websocket'));

fastify.register(async function (fastify) {
  fastify.get(
    '/',
    { websocket: true },
    (connection /* SocketStream */, req /* FastifyRequest */) => {
      connection.socket.on('message', (message) => {
        // message.toString() === 'hi from client'
        connection.socket.send('hi from server');
      });
    }
  );
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});

Then I try to connect within DevTools:

new WebSocket('ws://localhost:3000');

ws

When I try the basic example from the ws package, it works instantly (after enabling ESM):

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('error', console.error);

  ws.on('message', function message(data) {
    console.log('received: %s', data);
  });

  ws.send('something');
});

Video demo

https://github.com/fastify/fastify-websocket/assets/876666/2031e15f-a88e-4cb8-9525-01826befe8f7

Expected Behavior

I would expect to be able to connect to the WS server.

TimonVS commented 1 year ago

I'm sorry, I must have been tired. I got it working without any changes.