我有一个简单的客户端和服务器代码,它们使用websocket传递消息。当我尝试以字符串形式读取和发送消息时,它工作正常。我为此使用了aioconsole.ainput。但是我还没有办法通过网络套接字读取和发送二进制消息。它对inp_type = "str"
正常,不适用于inp_type = "binary"
。
客户端:
#!/usr/bin/python3.6
import asyncio
import websockets
import threading
import sys
from aioconsole import ainput
def send_input_binary(conn):
with sys.stdin.buffer as f:
while True:
inp = f.read(4)
conn.send(inp)
print('sent ' , inp)
async def send_input_async(conn):
while True:
inp = await ainput()
await conn.send(inp)
print('sent ' , inp)
async def start_client(uri):
async with websockets.connect(uri) as conn:
inp_type = "binary"
if (inp_type == "binary"):
t = threading.Thread(target=send_input_binary, args=[conn], daemon=True)
t.start()
t.join()
else:
await asyncio.wait([ send_input_async(conn)])
asyncio.get_event_loop().run_until_complete(start_client('ws://127.0.0.1:12321'))
服务器:
#!/usr/bin/python3.6
import asyncio
import websockets
async def echo(conn, path):
async for message in conn:
print('got ',message)
event_loop = asyncio.get_event_loop()
event_loop.run_until_complete(websockets.serve(echo, '127.0.0.1', 12321))
event_loop.run_forever()
建议我以某种方式从终端读取二进制输入并通过连接发送它。