HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
878 stars 142 forks source link

Is ws.on("connection") not working? #93

Open dhuber666 opened 6 years ago

dhuber666 commented 6 years ago

Hi,

I use following server route:

app.ws("/", (wss, req) => {
  console.log(req.user); // the user that has connected through websocket
  ws.on("connection", () => {
    console.log("Test");
  });
});

I never see that console statement when I connect my client to the server. Connection is successful however.

Here is the client code:

const ws = new WebSocket('ws://localhost:5000/');
    ws.onopen = () => {
        ws.send('Ping'); // Send the message 'Ping' to the server
    };

    ws.onmessage = (e) => {
        console.log(e.data);
    };

So it seems that the ws.on("connection") callback never runs. Is this not implemented, so I can only use ws.on("message") ?

HenningM commented 6 years ago

Hi @dhuber666,

Thanks for your interest in this library. I think you might be confusing the WebSocket class with the WebSocket.Server class. The object passed to your callback would be an instance of WebSocket. This class does not emit a 'connection' event.

This library actually routes the WS connection to the correct handler on the 'connection' event. So in most cases you could instead add your logic to the beginning of your app.ws handler/callback.

dhuber666 commented 6 years ago

HI @HenningM

Ah okay I get it. When the user comes to the route app.ws("/"...) he is already in the "connection" or connected phase? In fact I tested it out with just calling ws.send and it works perfectly.

app.ws("/", (ws, req) => {
    ws.send("hi") //works
}

That library is a blast! Thank you for that.

iasbm commented 5 years ago

Hello i am having similar issue, can you pls. check if you can help the issue https://github.com/HenningM/express-ws/issues/116 please?