Search code examples
pythonsocket.ionamespacesconnection

Python socketio add namespace after a connection is started


Looking at the python socketio documentation I defined a custom namespace:

import socketio


class MyCustomNamespace(socketio.ClientNamespace):

    def on_connect(self):
        pass

    def on_disconnect(self):
        pass

    def on_my_event(self, data):
        self.emit('my_response', data)

sio = socketio.Client()
sio.register_namespace(MyCustomNamespace('/chat'))
sio.connect("http://127.0.0.1:8888")
sio.emit("get", namespace="/chat")

Now this namespace works as long as I start the connection after registering the namespace. Makes sense. But is there a way to register namespaces after the connection has started? I get the following error:

  File "//src/pipeline/reporting/iam.py", line 30, in request_iam_credentials
    self.socket_client.emit(
  File "/usr/local/lib/python3.8/dist-packages/socketio/client.py", line 393, in emit
    raise exceptions.BadNamespaceError(
socketio.exceptions.BadNamespaceError: /chat is not a connected namespace.

Solution

  • Each namespace is kinda different space you have to connect to. If you don't use the namespace explicitely it's defaulted to '/'. Look:

    sio = socketio.Client()
    sio.emit("get") # emit before connect
    
    # socketio.exceptions.BadNamespaceError: / is not a connected namespace.
    

    Your situation is the same, but with /chat namespace - you connect to / but try emiting to /chat. You need to connect to /chat namespace by yourself:

    sio.connect("http://127.0.0.1:8888", namespaces=["/chat"]) # notice you can connect to more namespaces at once
    

    which is exactly what sio.connect do when you register namespace earlier.