3

I started an application using socketio as my websocket library, but now i need to use sharejs which does not support socketio. I would have changed the library but i have come a long way with socketio.

I tried using websocket ws library and it only seems to work when i place socketio and ws on different server ports.

I need to be able to use the same port for both of them. Please how do i do that. I found out that i can place them on different paths but i have not been able to do that successfully. I would really appreciate suggestions or answers.

makinwab
  • 43
  • 5

1 Answers1

1

This is a bit odd because express doesn't support proper routing for websocket requests. The first step is to pass 'destroy upgrade': false as an option to socket.io. Without this it will close websocket connections that are on paths it doesn't recognize.

However, closing erroneous websocket connections is still important. We'll tell ws when to do it, so we can accommodate both valid paths. We'll need to pass a function as the verifyClient option to the ws.Server constructor. The function should take arguments (info, next). You can use info.req.url to determine whether this is a path you're handling. There are 3 cases here:

  1. socket.io is handling this path. Return from the function without calling next. This tells ws to neither close the connection nor try to handle it.

  2. ws is handling this path. Call next(true) - this will tell ws to handle the handshake and then fire a connection event.

  3. No one is handling this request. Call next(false) - this tells ws to close the connection.

Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69