是否可以使用 python 的 asyncio 模块在多个工作进程之间共享一个套接字?
下面是一个启动服务器侦听端口 2000 的示例代码。当建立连接并且客户端发送字符串“S”时,服务器开始向客户端发送数据。但这一切只发生在一个 cpu 核心上。我怎样才能重写这个例子来利用所有的 cpu 内核?我查看了 asyncio 子进程模块,但不确定是否可以使用它来共享套接字,以便服务器可以同时接受来自多个工作进程的并行连接。
import asyncio
import datetime
clients = []
class MyServerProtocol(asyncio.Protocol):
def connection_made(self, transport):
self.transport = transport
self.peername = transport.get_extra_info("peername")
print("connection_made: {}".format(self.peername))
clients.append(self)
@asyncio.coroutine
def send_data_stream(self):
while True:
yield from asyncio.sleep(3)
if self in clients:
self.transport.write("{} {}\r\n".format('Endless stream of information', str(datetime.datetime.now())).encode())
print("sent data to: {}".format(self.peername))
else:
break
def data_received(self, data):
print("data_received: {}".format(data.decode()))
received = data.decode()
if received == "S":
asyncio.Task(self.send_data_stream())
def connection_lost(self, ex):
print("connection_lost: {}".format(self.peername))
clients.remove(self)
if __name__ == '__main__':
print("starting up..")
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
coro = loop.create_server(MyServerProtocol, port=2000)
server = loop.run_until_complete(coro)
for socket in server.sockets:
print("serving on {}".format(socket.getsockname()))
loop.run_forever()