How to connect to custom namespace socket.io websockets running with FastAPI + gunicorn which runs on a domain subpath?

193 views Asked by At

So I have a FastAPI app which is integrated with socketIO like so https://github.com/miguelgrinberg/python-socketio/blob/main/examples/server/asgi/fastapi-fiddle.py. The mantainer of python-socketio is pretty keen on this implementation.

Now we have multiple backend apps running on the same domain so my FastAPI app runs on my-domain.com/fast-api-app/. I have mounted the socketio app on the same level as my FastAPI app and so it should be available to connect at domain.com/fast-api-app/socket.io.

Now I have multiple namespaces within this socketio app and I want to connect to one of the namespaces from my React frontend. So essentially I want to connect to domain.com/fast-api-app/socket.io/custom-ns-1

Now I am not able to make this connection using my js socketio client instance. When I do the following

const socket = io(domain.com, {
  path: '/fast-api-app/socket.io/custom-ns-1',
  autoConnect: false,
  transports: ['websocket']
});

This ends up returning the socket instance connect to the '/' instance which I do not want as all of my custom logic is in ns-1.

When I run my FastAPI app locally, I am able to connect to my namespace like so

const wsHost = 'http://localhost:8000'
const wsPath = '/ns-1'

const manager = new Manager(wsHost, {
  reconnectionDelayMax: 10000,
  transports: ['websocket'],
  autoConnect: false
});

const socket = manager.socket(wsPath);

But the same thing gives me an error when I do the following

const wsHost = 'domain.com'
const wsPath = '/fast-api-app/ns-1'

const manager = new Manager(wsHost, {
  reconnectionDelayMax: 10000,
  transports: ['websocket'],
  autoConnect: false
});

const socket = manager.socket(wsPath);

Please any help would be appreciated, I have tried many other methods including using the Manager class but I am only able to connect to my default namespace and once the socket is returned I have no way of switching namespaces.

1

There are 1 answers

0
sidhant jain On

Seems very unintuitive but the answer posted here : Connect to Socket.IO server with specific path and namespace seems to work somehow.

Essentially what worked in my case was :

const socket = io('domain.com/ns-1', { path:'/fast-api-app/socket.io', transports: ['websocket'], autoConnect: false });