我正在尝试使用asyncio创建一个套接字服务器,我将异步侦听连接并获取每个连接的消息。但是我无法让它发挥作用。
这是我的服务器代码:
import asyncio
import socket, sys
from concurrent.futures import ProcessPoolExecutor
def print_output(csock, loop):
while 1:
print('gotcha')
msg = csock.recv(1024)
if not msg:
pass
else:
print ("Client send: " + msg)
def s_listen(loop):
while True:
(csock, adr) = sock.accept()
print('start another process')
asyncio.ensure_future(loop.run_in_executor(executor, print_output, csock, loop))
print('done')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #reuse tcp
sock.bind(('', 12345))
sock.listen(5)
executor = ProcessPoolExecutor()
loop = asyncio.get_event_loop()
listener = asyncio.ensure_future(loop.run_in_executor(executor,s_listen,loop))
print('here')
虽然这是我的客户代码
import socket, sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 12345))
sock.send(b"Hello I'm Client.\r\n")
我可以获得功能" s_listen"异步运行但代码被" print_output"功能
我是asyncio的新手,有人可以帮忙吗? 谢谢!
答案 0 :(得分:0)
Asyncio提供了一个名为stream的基于协程的API来管理套接字客户端和服务器。这是tcp echo server的user documentation的修改版本:
import asyncio
# Client handler
async def handle_echo(reader, writer):
while not reader.at_eof():
data = await reader.read(100)
message = data.decode().strip()
print('Client sent: ' + message)
writer.close()
# Start the server
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '', 12345, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
您可以使用netcat客户端测试此示例:
# Client
$ ncat localhost 12345
hello,
world!
# Server
$ python3.5 server.py
Serving on ('0.0.0.0', 12345)
Client sent: hello,
Client sent: world!