Websocket Endpoints and Express Router

Viewed 1086

I was trying to implement web-sockets (npm ws) in my express application, but got stuck on how I should implement my websockets so that they work with express router.

Currently, my endpoints look like this...

router.post('/create-note', jwtAuthentication, NotesController.createNote);
router.get('/get-notes/:id',jwtAuthentication, NotesController.getUserNotes);
router.??('/socket-endpoint', NotesController.wssNote);

As you can see, I am unsure of what method to call on my router. I have tried using 'get' and 'post, but for some reason it only works after I try a second connection on postman. (I click connect, nothing happens, I then click disconnect and connect again and it works.)

I know that I can pass in the path when creating the WebSocketServer...

var wss = new WebSocketServer({server: server, path: "/hereIsWS"});

This does work, but if it is possible to use routers with web-sockets, I think it would make my whole project much cleaner and more organised.

I have come across people recommending 'express-ws', but was wondering if there was a better method to solve my problem, specifically a method that does not involve other packages.

Thanks in advance!

1 Answers

You do not use Express routers with webSockets. That's not the proper architecture for webSockets. Your webSocket server can share an http server with Express, but that's pretty much all the two have to do with one another.

webSockets connect on a particular path which you pass to the webSocketServer() constructor as it appears you already know. Once they are connected they stay connected and form a TCP pipe that you can send packets of data from client to server or from server to client. There is no Express routing used for that.

You can create your own message handling within a webSocket message by creating a message name as part of the webSocket payload if you want (this is something that the socket.io layer on top of webSockets does for you), but it has nothing to do with Express at that point. That's just in how you choose to handle the incoming webSocket packets.

if there was a better method to solve my problem

What is your specific problem? Perhaps if you stated the specific problem you want help with, we could provide further assistance.

To handle incoming webSocket messages, you can follow the example in the ws server doc:

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

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

To further break up this to handle different types of incoming webSocket messages, you have to create your own message format that you can branch on or use socket.io instead on both client and server that does that for you.

Related