apteryxxyz / next-ws

Add support for WebSockets in Next.js app directory.
https://npmjs.com/next-ws
171 stars 12 forks source link

WebSockerServer not firing 'on connection' event #32

Open FlynnHillier opened 4 months ago

FlynnHillier commented 4 months ago

I am trying to establish some listeners on my server using the WebSocketServer that is exposed within the SOCKET route.

Given the following simple code in a route.ts file:

function applyWSSListeners(wss: WebSocketServer) {
  console.log("applying listener");

  wss.once("connection", (socket) => {
    console.log("connection!");
  });
}

export async function SOCKET(
  client: WebSocket,
  request: IncomingMessage,
  server: WebSocketServer,
) {
  applyWSSListeners(server); 
}

I observe that applyWSSListeners is being called, as I can see 'applying listener' being logged in the console when my page is refreshed and the Socket provider makes a request to the route.ts endpoint (as expected).

However, I never see the 'connection!' string logged to the console. I would understand if this perhaps happened on the first connection as 'applyWSSListeners' is perhaps called after the socket connected - however I cannot understand why I still do not see the message logged in any subsequent connections (after applyWSSListeners has definitely been called).

I am sure the sockets are connecting as when I log server I can see the WebSocket objects in a Set.

I created this simple example by following the simple example provided by the ws docs .

Could anyone please share how they've handled setting up listeners on the WebSocketServer object?