【发布时间】:2013-03-18 10:22:42
【问题描述】:
我正在尝试利用 multiprocessing 模块的客户端/服务器架构来促进我的 Python 脚本之间的通信。我希望能够使用asyncore 在主事件循环之外实现一个单独的连接侦听器。我该怎么做?
虽然没有关于如何执行此操作的外部文档,但我尝试使用来自multiprocessing.Listener 的侦听器套接字构造一个基本的asyncore.dispatcher:
import asyncore
import socket
from multiprocessing.connection import Listener, Client
class ConnectionListener(asyncore.dispatcher):
def __init__(self, ln):
asyncore.dispatcher.__init__(self)
self.set_socket(ln._listener._socket)
def handle_accepted(self, sock, addr):
print("Accepted a client!")
if __name__ == "__main__":
address = ('localhost', 19378)
try:
ln = Listener(address)
x = ConnectionListener(ln)
while True:
asyncore.loop()
except socket.error:
c = Client(address)
print("Client is trying to connect")
当服务器循环时,它永远不会触发handle_accepted。
【问题讨论】:
标签: python sockets event-handling multiprocessing asyncore