miguelgrinberg / python-socketio

Python Socket.IO server and client
MIT License
3.87k stars 575 forks source link

"socketio.Client" automatically disconnects from the server #1343

Closed yan990703 closed 1 month ago

yan990703 commented 1 month ago

Describe the bug "socketio.Client" always disconnects automatically after receiving data sent by the server "send_file" event, and then triggers the automatic reconnection mechanism. This has nothing to do with the size of the file, even a text file with only one or two characters can trigger the file. Clients created using "socketio.AsyncClient" will not have this problem.

To Reproduce Steps to reproduce the behavior:

import os

import socketio

d = '3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4'
sio = socketio.Client(logger=True, engineio_logger=True)

@sio.event
def connect():
    print('connected to server')
    sio.emit('join_room_p', data=d)

@sio.on('connectionSuccess')
def connection_success(data):
    print('connectionSuccess', data)

@sio.on('send_file')
def send_file(data):
    if data.get('sender') is not None and data.get('sender') != d:
        if isinstance(data.get('data'), bytes):
            with open(os.path.join('D:\\PycharmProject\\SocketIO-Cloud\\testClient', data['filename']), 'ab') as f:
                f.write(data.get('data'))
            print('receive file', data['filename'])
        else:
            with open(os.path.join('D:\\PycharmProject\\SocketIO-Cloud\\testClient', data['filename']), 'a',
                      encoding='utf-8') as f:
                f.write(data.get('data'))
            print('receive file', data['filename'])

    if data.get('sending_complete') is True:
        sio.emit("send_file", data={
            "role": data.get('role'),
            "filename": data.get('filename'),
            "result": 0,
        })

def get_auth_data():
    return {
        'role': 'printer',
        'uid': d,
        'key': "123456"
    }

def start_server():
    sio.connect('http://192.168.0.254:3001/', auth=get_auth_data)
    sio.wait()

if __name__ == '__main__':
    start_server()

Using the above code, sending a file's byte type data to the "send_file" event triggers the problem, and you can see a log like this

Expected behavior A clear and concise description of what you expected to happen.

Logs

This is Client Logs


Attempting polling connection to http://192.168.0.254:3001/socket.io/?transport=polling&EIO=4
Polling connection accepted with {'sid': 'nr-HRtYmK_B1S18KAAA2', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
Engine.IO connection established
Sending packet MESSAGE data 0{"role":"printer","uid":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","key":"123456"}
Attempting WebSocket upgrade to ws://192.168.0.254:3001/socket.io/?transport=websocket&EIO=4
WebSocket upgrade was successful
Received packet NOOP data 
Received packet MESSAGE data 2["connection_success",{}]
Received event "connection_success" [/]
Received packet MESSAGE data 0{"sid":"bXRS8jlAfRR1VfHhAAA3"}
Namespace / is connected
Emitting event "join_room_p" [/]
Sending packet MESSAGE data 2["join_room_p","3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"]
Received packet MESSAGE data 2["print_status_p",{"role":"user","printer_id":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","mode":"set","freq":1.5}]
Received event "print_status_p" [/]
Received packet MESSAGE data 2["set_temp_export_p",{"role":"user","printer_id":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","mode":"set","freq":1.5}]
Received event "set_temp_export_p" [/]
connected to server
Received packet MESSAGE data 51-["send_file",{"role":"gD7PJCkWWonzZDiIAAA5","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":false,"receiver":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"}]
Received packet MESSAGE data <binary>
Received event "send_file" [/]
receive file aaa.txt
Received packet PING data 
Sending packet PONG data 
Received packet MESSAGE data 51-["send_file",{"role":"gD7PJCkWWonzZDiIAAA5","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":true,"md5":"74b87337454200d4d33f80c4663dc5e5","receiver":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"}]
WebSocket connection was closed, aborting
Waiting for write loop task to end
Exiting write loop task
Engine.IO connection dropped
Connection failed, new attempt in 0.83 seconds
Exiting read loop task
Attempting polling connection to http://192.168.0.254:3001/socket.io/?transport=polling&EIO=4
Polling connection accepted with {'sid': '8rnJRTYIr9S9ZEkmAAA6', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
Engine.IO connection established
Sending packet MESSAGE data 0{"role":"printer","uid":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","key":"123456"}
Attempting WebSocket upgrade to ws://192.168.0.254:3001/socket.io/?transport=websocket&EIO=4
WebSocket upgrade was successful
Received packet NOOP data 
Received packet MESSAGE data 2["connection_success",{}]
Received event "connection_success" [/]
Received packet MESSAGE data 0{"sid":"e6ZmjDFPX2iCZ-fkAAA7"}
Namespace / is connected
Emitting event "join_room_p" [/]
Sending packet MESSAGE data 2["join_room_p","3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"]
Reconnection successful
Received packet MESSAGE data 2["print_status_p",{"role":"user","printer_id":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","mode":"set","freq":1.5}]
Received event "print_status_p" [/]
Received packet MESSAGE data 2["set_temp_export_p",{"role":"user","printer_id":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","mode":"set","freq":1.5}]
Received event "set_temp_export_p" [/]

This is Server Logs


0HPzQw8LzbH-nlfJAAAC: Received packet MESSAGE data 2["share_file",{"role":"4OelWVjHv_GEqh7qAAAD","sender":"1033599272@qq.com","receiver":["3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"]}]
received event "share_file" from 4OelWVjHv_GEqh7qAAAD [/]
0HPzQw8LzbH-nlfJAAAC: Received packet MESSAGE data 51-["send_file",{"role":"4OelWVjHv_GEqh7qAAAD","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":false}]
0HPzQw8LzbH-nlfJAAAC: Received packet MESSAGE data <binary>
received event "send_file" from 4OelWVjHv_GEqh7qAAAD [/]
emitting event "send_file" to vZd8VleP7b4A_BslAAAF [/]
3ACXDwJTX6KS1fItAAAE: Sending packet MESSAGE data 51-["send_file",{"role":"4OelWVjHv_GEqh7qAAAD","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":false,"receiver":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"}]
3ACXDwJTX6KS1fItAAAE: Sending packet MESSAGE data <binary>
2024-06-04 14:36:58,256 - app_view - INFO - <on_send_file>  1033599272@qq.com send file chunk to 3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4 success
0HPzQw8LzbH-nlfJAAAC: Received packet MESSAGE data 51-["send_file",{"role":"4OelWVjHv_GEqh7qAAAD","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":true,"md5":"74b87337454200d4d33f80c4663dc5e5"}]
0HPzQw8LzbH-nlfJAAAC: Received packet MESSAGE data <binary>
received event "send_file" from 4OelWVjHv_GEqh7qAAAD [/]
emitting event "send_file" to vZd8VleP7b4A_BslAAAF [/]
3ACXDwJTX6KS1fItAAAE: Sending packet MESSAGE data 51-["send_file",{"role":"4OelWVjHv_GEqh7qAAAD","data":{"_placeholder":true,"num":0},"filename":"aaa.txt","sender":"1033599272@qq.com","sending_complete":true,"md5":"74b87337454200d4d33f80c4663dc5e5","receiver":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4"}]
3ACXDwJTX6KS1fItAAAE: Sending packet MESSAGE data <binary>
2024-06-04 14:36:59,277 - app_view - INFO - <on_send_file>  1033599272@qq.com send file chunk to 3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4 success
cHsSK9Df7u14xXWFAAAG: Sending packet OPEN data {'sid': 'cHsSK9Df7u14xXWFAAAG', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000}
2024-06-04 14:37:00,606 - app_view - INFO - <on_connect> 3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4 authentication successfully
2024-06-04 14:37:00,607 - app_view - INFO - <on_join_room_printer> 3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4 join room p1
cHsSK9Df7u14xXWFAAAG: Received request to upgrade to websocket
cHsSK9Df7u14xXWFAAAG: Upgrade to websocket successful
cHsSK9Df7u14xXWFAAAG: Received packet MESSAGE data 0{"role":"printer","uid":"3914-9CF8-1B70-11EF-A968-E89C-25DE-F6B4","key":"123456"}
emitting event "connection_success" to Rni1Vv4KSJNLiCu-AAAH [/]

Additional context I have provided two files, which create the client in AsyncClient and Client respectively. They receive the same data in the send_file event, and the client created by AsyncClient will not be disconnected.

SimpleClient.txt

AsyncClient.txt

miguelgrinberg commented 1 month ago

This is likely because you are sending an empty binary payload in your last emit. The sync websocket client does not like empty binary packets, it decides the connection has died. The async websocket client does not have this limitation.

yan990703 commented 1 month ago

这可能是因为您在上次发出时发送了一个空的二进制有效负载。同步 websocket 客户端不喜欢空的二进制数据包,它认为连接已死亡。异步 websocket 客户端没有此限制。

I see, I do send an empty binary as the flag bit after each send! Thank you very much