socket.io icon indicating copy to clipboard operation
socket.io copied to clipboard

Allow different paths for http and ws

Open sunshineo opened this issue 1 year ago • 5 comments

We are using Azure API management service and it has this limitation: We have to create 2 separated API for http and ws protocol, and in 2 separate API, we need to have different url suffix. So I end up with

https://api.mycompany.com/chat-service-broadcast/socket.io
wss://api.mycompany.com/chat-service-broadcast-websocket/socket.io

My frontend code:

const PATH = '/chat-service-broadcast/socket.io';

export const socket = io(URL, {
  path: PATH,
  autoConnect: false,
});

And this works on the http call, but then it tries to call wss://api.mycompany.com/chat-service-broadcast/socket.io and fail

Is it very difficult to allow different path? Is there a way I can intercept the websocket call and modify the url before it goes out?

sunshineo avatar May 22 '23 06:05 sunshineo

In that case, you should be able to overwrite the path when receiving the open event:

const socket = io();

socket.io.on("open", () => {
  socket.io.engine.opts.path = "/chat-service-broadcast-websocket/socket.io/";
});

So the WebSocket transport will use the given path.

darrachequesne avatar May 23 '23 06:05 darrachequesne

I got

Property 'opts' is private and only accessible within class 'Socket'.

sunshineo avatar May 30 '23 22:05 sunshineo

@darrachequesne , any way to expose that? Is there a way to overwrite extend to make it compile?

sunshineo avatar Jun 21 '23 16:06 sunshineo

@sunshineo you can now use the transportOptions option:

const socket = io({
  path: "/chat-service-broadcast/socket.io",
  transportOptions: {
    websocket: {
      path: "/chat-service-broadcast-websocket/socket.io"
    }
  }
});

darrachequesne avatar Jul 04 '23 07:07 darrachequesne

@sunshineo did you have much luck with this? I am struggling to get socket.io + APIM working.

harveyconnor avatar Dec 08 '23 02:12 harveyconnor

I think this can be closed now. Please reopen if needed.

darrachequesne avatar Mar 27 '24 09:03 darrachequesne

We end up did not turn on ws at all and completely just relied on http long poll. So far it works totally fine. So I cannot provide any info on if this works or not.

sunshineo avatar Mar 27 '24 21:03 sunshineo