我实现了一个简单的服务器来与客户端通信。大约30秒后,服务器宣布客户端已断开连接。我试图增加服务器的ping_travler
和ping_timeout
参数,但这似乎没有帮助。
我想知道断开连接是由服务器还是由客户端引起的。我们如何保持客户端和服务器之间的连接?
我的代码如下:
服务器:
# coding:utf-8
import json
import socketio
import uvicorn
# ping_travler=60, ping_timeout=300, always_connect=True
sio = socketio.AsyncServer(async_mode='asgi')
app = socketio.ASGIApp(sio)
@sio.event
def disconnect(sid):
print('disconnect:', sid)
@sio.event
def connect(sid, environ):
sio.start_background_task(target=send_message)
print("connect ", sid)
@sio.on('message', namespace='/server_conn')
async def receive_message(sid, data):
pass
async def send_message():
while True:
await sio.sleep(0.00001)
await sio.emit('receive_message', json.dumps('123'))
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=5000)
客户:
# coding:utf-8
import asyncio
import json
import time
from flask_socketio import socketio
sio = socketio.AsyncClient(logger=True, engineio_logger=False)
t = time.time()
@sio.event
def connect():
sio.start_background_task(target=send_message)
@sio.event
def disconnect():
print('client disconnected')
async def send_message():
while True:
await sio.sleep(0.2)
await sio.send(json.dumps('123'), namespace='/server_rece')
@sio.event
async def receive_message(message):
print(message)
print(time.time() - t) # Disconnected in about 30 seconds
async def start_sio_server():
await sio.connect('http://127.0.0.1:5000')
def main():
LOOP = asyncio.new_event_loop()
asyncio.set_event_loop(LOOP)
LOOP.run_until_complete(start_sio_server())
LOOP.run_forever()
if __name__ == '__main__':
main()
谢谢。