suhaildawood / SvelteKit-integrated-WebSocket

First-class support for WebSockets within SvelteKit by attaching a WebSocket server to the global state.
MIT License
222 stars 13 forks source link

Messages not coming through from another client #3

Open neves-io opened 1 year ago

neves-io commented 1 year ago

Thanks for this repo - it seems to do what we're looking for!

I'm new to web sockets and I'm struggling with getting anything to appear in the log that isn't sent from within SvelteKit.

I can successfully connect to the ws server with ws://localhost:3004/websocket. I'm using node-red and also the web socket test extension.

When I try to send a message to the log from either node-red or the test extension, nothing appears in the log. Reading works fine.

suhaildawood commented 1 year ago

Glad it was helpful! From what I understand you've successfully set up the WebSocket client from the browser but aren't receiving messages from the server? Does it log anything if you make a fetch call to the test endpoint? If you have something else connecting to the WebSocket server that you'd like to pass onto other clients you need to coordinate that on the server.

In the example endpoint we loop through all the clients on the server, effectively broadcasting the message:

locals.wss.clients.forEach(client => {
    if (client.readyState === 1) {
      client.send(`Hello from the GET handler at ${new Date().toLocaleString()}`);
    }
  });

This setup is pretty barebones so there's no context of which client is who. In a real word application you'd probably use something like an authentication token or identifiable ID within the incoming payload to figure out which client is which and coordinate communication based on your intended use case.