python 使用websocket为什么我能主动发 就不能收哎 await send(websocket)可以,再加上await rev()就不行了
clients = set()
newValue = ''
oldValue = ''
msg = ''
# 读串口
async def readLoop():
global newValue
print('开始读串口')
port = "COM3" # 修改为自己的串口
bps = 9600
bytesize = 8
ser = serial.Serial(port, int(bps), int(bytesize),
timeout=1, parity=serial.PARITY_NONE, stopbits=1)
while True:
buffer = await asyncio.to_thread(ser.readline) # 异步读取串口数据
buffer = buffer.decode().strip()
print(buffer)
if buffer == '':
continue
if buffer == 'a':
newValue = 'a'
elif buffer == 'b':
newValue = 'b'
# WebSocket 服务器
async def eho(websocket, path):
global newValue, oldValue, clients
# clients.clear()
clients.add(websocket)
print(len(clients), newValue, oldValue)
await send(websocket)
await rev(websocket)
# 发消息
async def send(websocket):
global newValue, oldValue
while True:
if newValue != oldValue:
websockets.broadcast(clients, newValue)
oldValue = newValue
else:
await asyncio.sleep(random.random() * 1)
# 接收消息
async def rev(websocket):
global msg
while True:
msg = await websocket.recv()
print(msg)
# 主函数
def main():
t1 = Thread(target=lambda: asyncio.run(readLoop())) # 在新线程中异步执行readLoop函数
t1.start()
start_server = websockets.serve(eho, "127.0.0.1", 5678)
print('Websocket 服务器已启动')
try:
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
print('程序已结束')
t1.join() # 关闭线程