是否可以使用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()
答案 0 :(得分:3)
您可以查看,例如https://github.com/KeepSafe/aiohttp/blob/master/examples/mpsrv.py,例如多进程服务器。