为什么 Python 中 SocketIO 的 sio.emit 调用需要 7-10 秒才能到达?
我在树莓派上。我想从串行读取,解析命令,然后立即向通过 SocketIO 连接的客户端发送更新。
根据我的理解,串行需要一个 while true 循环,因此我在单独的线程中执行它。我将所有代码精简为下面的最低限度示例。
问题:从串口接收数据后,函数“sendMessage”立即按预期执行,来自socketIO的Logger提示
emmiting event "updateRequest" to all [/]
也立即显示。但实际数据需要 7 到 10 秒才能通过本地网络到达客户端。当通过其他方式触发“更新”时,例如对 asyncio 的 POST 请求(不包括在下面的示例代码中),则不存在此问题。
我检查了“容易实现的目标”,例如更改串行波特率或降低串行超时,但我很确定我从根本上误解了有关Python线程的一些内容,因为我对此非常陌生。
你能帮忙吗?
from aiohttp import web
import socketio
import threading
import serial
import asyncio
port = '/dev/ttyS0'
baud = 115200
serial_port = serial.Serial(port, baud, timeout=0.2)
sio = socketio.AsyncServer(logger=True, async_mode='aiohttp', cors_allowed_origins='*')
app = web.Application()
sio.attach(app)
def read_from_port(ser):
while True:
reading = ser.readline().decode('utf-8')
if(len(reading)):
handle_antenna_feedback(reading)
def handle_antenna_feedback(data):
asyncio.run(sendMessage())
async def sendMessage():
await sio.emit('updateRequest', "{}")
if __name__ == '__main__':
thread = threading.Thread(target=read_from_port, args=(serial_port,))
thread.start()
web.run_app(app,host="0.0.0.0", port=3000)
I am on a Raspberry Pi. I want to read from Serial, parse the command and then immediately send an update to a client connected via SocketIO.
In my understanding, Serial needs a while true - loop, so I execute that in a seperate thread. I stripped all my code down to the bare minimum example down below.
Problem: After receiving data from Serial, function "sendMessage" is executed immediately as intended, Logger prompt from socketIO shows
emmiting event "updateRequest" to all [/]
immediately as well. But the actual data takes between 7 and 10 seconds to arrive at the client over local network. This problem does not exist when the "update" is triggered by other means, e.g. a POST-Request to asyncio (not included in the example code below).
I checked the "low hanging fruit" like changing the Serial-Baudrate or lowering the Serial-Timeout but I am pretty sure I fundamentally misunderstood something about python threading as I am very new to this.
Can you help?
from aiohttp import web
import socketio
import threading
import serial
import asyncio
port = '/dev/ttyS0'
baud = 115200
serial_port = serial.Serial(port, baud, timeout=0.2)
sio = socketio.AsyncServer(logger=True, async_mode='aiohttp', cors_allowed_origins='*')
app = web.Application()
sio.attach(app)
def read_from_port(ser):
while True:
reading = ser.readline().decode('utf-8')
if(len(reading)):
handle_antenna_feedback(reading)
def handle_antenna_feedback(data):
asyncio.run(sendMessage())
async def sendMessage():
await sio.emit('updateRequest', "{}")
if __name__ == '__main__':
thread = threading.Thread(target=read_from_port, args=(serial_port,))
thread.start()
web.run_app(app,host="0.0.0.0", port=3000)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论