Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncClient automatically disconnects if not explicitly passing 'namespaces' #1351

Closed
notnitsuj opened this issue Jun 18, 2024 · 0 comments
Closed
Assignees
Labels

Comments

@notnitsuj
Copy link

I'm testing out python-socketio==5.11.2 with a Python client before plugging it into my real application. At first, I thought events other than message don't work, but after logging I found that the client automatically disconnect after the connect event handler finishes.

One more problem I found is that the catch-all event handlers don't work for both client and server.

My server code with uvicorn test_server:app:

import socketio


sio = socketio.AsyncServer(logger=True, async_mode='asgi', engineio_logger=True)
app = socketio.ASGIApp(socketio_server=sio)

@sio.event
async def connect(sid, environ, auth):
    await sio.emit("message", data={"data": "message connected"})
    await sio.emit("chat", data={"data": "chat connected"})


@sio.event
async def disconnect(sid):
    print(f"Client disconnected - Session ID: {sid}")

@sio.event
async def message(sid, data):
    print(f"message {data}")

@sio.on("chat")
async def on_chat(sid, data):
    print(f"chat {data}")

@sio.on('*', namespace='*')
async def any_event_any_namespace(event, namespace, sid, data):
    print(f"Event {event} - Namespace {namespace} - SID {sid} - Data {data}")

My client code:

import socketio
import asyncio
 
# asyncio
sio = socketio.AsyncClient(logger=True, engineio_logger=True)
 
@sio.event
async def connect():
    print("Connected to http://127.0.0.1:8000")
    await sio.emit("message", {"message": "connected"})
    await sio.emit("chat", data={"data": "chat connected"})

    print("disconnect here?")
 
@sio.event
def connect_error(data):
    print(f"Connection error: {data}")
 
@sio.event
def disconnect():
    print("Disconnected!")
 
@sio.on('*', namespace='*')
async def any_event_any_namespace(event, namespace, sid, data):
    print(f"Event {event} - Namespace {namespace} - SID {sid} - Data {data}")
 
@sio.event
async def message(data):
    print(f"message {data}")

@sio.event
async def chat(data):
    print(f"chat {data}")

async def main():
    try:
        await sio.connect('http://127.0.0.1:8000', retry=True)
    except:
        print("refused")
 
    print(1)
    await sio.emit("message", {"message": "1"})
 
    print(2)
    await sio.emit("chat", {"chat": "2"})
 
    print(3)
    await sio.emit("chat", {"chat": "3"})
    
 
    print(sio.transport())

    await asyncio.sleep(1)
    await sio.disconnect()
 
if __name__ == '__main__':
    asyncio.run(main())

The logs in this case are:

###Server
9gmgwsDDMXSZarbbAAAA: Sending packet OPEN data {'sid': '9gmgwsDDMXSZarbbAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
INFO:     127.0.0.1:35558 - "GET /socket.io/?transport=polling&EIO=4&t=1718734956.0483625 HTTP/1.1" 200 OK
9gmgwsDDMXSZarbbAAAA: Received request to upgrade to websocket
INFO:     ('127.0.0.1', 35558) - "WebSocket /socket.io/?transport=websocket&EIO=4&sid=9gmgwsDDMXSZarbbAAAA&t=1718734956.050288" [accepted]
INFO:     connection open
9gmgwsDDMXSZarbbAAAA: Upgrade to websocket successful
9gmgwsDDMXSZarbbAAAA: Received packet MESSAGE data 0*,{}
message async handler error
Traceback (most recent call last):
  File "/home/mp/.local/lib/python3.10/site-packages/engineio/async_server.py", line 483, in run_async_handler
    return await self.handlers[event](*args)
  File "/home/mp/.local/lib/python3.10/site-packages/socketio/async_server.py", line 667, in _handle_eio_message
    pkt = self.packet_class(encoded_packet=data)
  File "/home/mp/.local/lib/python3.10/site-packages/socketio/packet.py", line 43, in __init__
    self.attachment_count = self.decode(encoded_packet) or 0
  File "/home/mp/.local/lib/python3.10/site-packages/socketio/packet.py", line 114, in decode
    self.data = self.json.loads(ep)
  File "/home/mp/.local/lib/python3.10/site-packages/engineio/json.py", line 16, in loads
    return original_loads(*args, **kwargs)
  File "/usr/lib/python3.10/json/__init__.py", line 359, in loads
    return cls(**kw).decode(s)
  File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.10/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
9gmgwsDDMXSZarbbAAAA: Received packet MESSAGE data 0{}
emitting event "message" to all [/]
9gmgwsDDMXSZarbbAAAA: Sending packet MESSAGE data 2["message",{"data":"message connected"}]
emitting event "chat" to all [/]
9gmgwsDDMXSZarbbAAAA: Sending packet MESSAGE data 2["chat",{"data":"chat connected"}]
9gmgwsDDMXSZarbbAAAA: Sending packet MESSAGE data 0{"sid":"Fz9W8X_nDDAi1eIzAAAB"}
9gmgwsDDMXSZarbbAAAA: Received packet MESSAGE data 2["message",{"message":"connected"}]
received event "message" from Fz9W8X_nDDAi1eIzAAAB [/]
message {'message': 'connected'}
9gmgwsDDMXSZarbbAAAA: Received packet MESSAGE data 2["chat",{"data":"chat connected"}]
received event "chat" from Fz9W8X_nDDAi1eIzAAAB [/]
chat {'data': 'chat connected'}
INFO:     connection closed
Client disconnected - Session ID: Fz9W8X_nDDAi1eIzAAAB
### Client
Attempting polling connection to http://127.0.0.1:8000/socket.io/?transport=polling&EIO=4
Polling connection accepted with {'sid': '9gmgwsDDMXSZarbbAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
Engine.IO connection established
Sending packet MESSAGE data 0*,{}
Sending packet MESSAGE data 0{}
Attempting WebSocket upgrade to ws://127.0.0.1:8000/socket.io/?transport=websocket&EIO=4
WebSocket upgrade was successful
Received packet NOOP data 
Received packet MESSAGE data 2["message",{"data":"message connected"}]
Received event "message" [/]
message {'data': 'message connected'}
Received packet MESSAGE data 2["chat",{"data":"chat connected"}]
Received event "chat" [/]
chat {'data': 'chat connected'}
Received packet MESSAGE data 0{"sid":"Fz9W8X_nDDAi1eIzAAAB"}
Namespace / is connected
Connected to http://127.0.0.1:8000
Emitting event "message" [/]
Sending packet MESSAGE data 2["message",{"message":"connected"}]
Emitting event "chat" [/]
Sending packet MESSAGE data 2["chat",{"data":"chat connected"}]
disconnect here?
Sending packet MESSAGE data 1
Sending packet CLOSE data None
Engine.IO connection dropped
Write loop: WebSocket connection was closed, aborting
Exiting write loop task
Server sent close packet data None, aborting
Waiting for write loop task to end
Exiting read loop task
refused
1
Emitting event "message" [/]
2
Emitting event "chat" [/]
3
Emitting event "chat" [/]
websocket

The disconnect message is sent immediately after the connect event handler finishes. The server couldn't handle this disconnect message and I couldn't even trace which caused that message async handler error if I didn't have the client logs.

When I add namespaces="/" to sio.connect the client works fine. This, however, does not make sense because the logs in the previous case state that Namespace / is connected.

Attempting polling connection to http://127.0.0.1:8000/socket.io/?transport=polling&EIO=4
Polling connection accepted with {'sid': 'rMAzXhR3GSk2y4g6AAAC', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
Engine.IO connection established
Sending packet MESSAGE data 0{}
Attempting WebSocket upgrade to ws://127.0.0.1:8000/socket.io/?transport=websocket&EIO=4
WebSocket upgrade was successful
Received packet NOOP data 
Received packet MESSAGE data 2["message",{"data":"message connected"}]
Received event "message" [/]
message {'data': 'message connected'}
Received packet MESSAGE data 2["chat",{"data":"chat connected"}]
Received event "chat" [/]
chat {'data': 'chat connected'}
Received packet MESSAGE data 0{"sid":"JiKwU6DpIR1chjXxAAAD"}
Namespace / is connected
Connected to http://127.0.0.1:8000
Emitting event "message" [/]
Sending packet MESSAGE data 2["message",{"message":"connected"}]
Emitting event "chat" [/]
Sending packet MESSAGE data 2["chat",{"data":"chat connected"}]
disconnect here?
1
Emitting event "message" [/]
Sending packet MESSAGE data 2["message",{"message":"1"}]
2
Emitting event "chat" [/]
Sending packet MESSAGE data 2["chat",{"chat":"2"}]
3
Emitting event "chat" [/]
Sending packet MESSAGE data 2["chat",{"chat":"3"}]
websocket
Sending packet MESSAGE data 1
Sending packet CLOSE data None
Engine.IO connection dropped
Disconnected!
Write loop: WebSocket connection was closed, aborting
Exiting write loop task
Server sent close packet data None, aborting
Waiting for write loop task to end
Exiting read loop task

Server logs are correct:

Server initialized for asgi.
INFO:     Started server process [144165]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
kUs1XS7BRhj9aPAWAAAA: Sending packet OPEN data {'sid': 'kUs1XS7BRhj9aPAWAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
INFO:     127.0.0.1:58698 - "GET /socket.io/?transport=polling&EIO=4&t=1718735272.3950653 HTTP/1.1" 200 OK
kUs1XS7BRhj9aPAWAAAA: Received request to upgrade to websocket
INFO:     ('127.0.0.1', 58698) - "WebSocket /socket.io/?transport=websocket&EIO=4&sid=kUs1XS7BRhj9aPAWAAAA&t=1718735272.3968916" [accepted]
INFO:     connection open
kUs1XS7BRhj9aPAWAAAA: Upgrade to websocket successful
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 0{}
emitting event "message" to all [/]
kUs1XS7BRhj9aPAWAAAA: Sending packet MESSAGE data 2["message",{"data":"message connected"}]
emitting event "chat" to all [/]
kUs1XS7BRhj9aPAWAAAA: Sending packet MESSAGE data 2["chat",{"data":"chat connected"}]
kUs1XS7BRhj9aPAWAAAA: Sending packet MESSAGE data 0{"sid":"JI7P4AqFkkaE2u9DAAAB"}
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 2["message",{"message":"connected"}]
received event "message" from JI7P4AqFkkaE2u9DAAAB [/]
message {'message': 'connected'}
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 2["chat",{"data":"chat connected"}]
received event "chat" from JI7P4AqFkkaE2u9DAAAB [/]
chat {'data': 'chat connected'}
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 2["message",{"message":"1"}]
received event "message" from JI7P4AqFkkaE2u9DAAAB [/]
message {'message': '1'}
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 2["chat",{"chat":"2"}]
received event "chat" from JI7P4AqFkkaE2u9DAAAB [/]
chat {'chat': '2'}
kUs1XS7BRhj9aPAWAAAA: Received packet MESSAGE data 2["chat",{"chat":"3"}]
received event "chat" from JI7P4AqFkkaE2u9DAAAB [/]
chat {'chat': '3'}
INFO:     connection closed
Client disconnected - Session ID: JI7P4AqFkkaE2u9DAAAB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants