栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python SocketServer:发送到多个客户端?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python SocketServer:发送到多个客户端?

您想在这里查看asyncore。您正在客户端调用的套接字操作被阻止(在接收到一些数据或发生超时之前不会返回),这使得很难侦听主机发送的消息,并使客户端实例排队将数据发送到同一时间。异步应该从您那里抽象出基于超时的轮询循环。

这是代码“样本”-如果有任何不清楚的地方,请告诉我:

from __future__ import print_functionimport asyncoreimport collectionsimport loggingimport socketMAX_MESSAGE_LENGTH = 1024class RemoteClient(asyncore.dispatcher):    """Wraps a remote client socket."""    def __init__(self, host, socket, address):        asyncore.dispatcher.__init__(self, socket)        self.host = host        self.outbox = collections.deque()    def say(self, message):        self.outbox.append(message)    def handle_read(self):        client_message = self.recv(MAX_MESSAGE_LENGTH)        self.host.broadcast(client_message)    def handle_write(self):        if not self.outbox: return        message = self.outbox.popleft()        if len(message) > MAX_MESSAGE_LENGTH: raise ValueError('Message too long')        self.send(message)class Host(asyncore.dispatcher):    log = logging.getLogger('Host')    def __init__(self, address=('localhost', 0)):        asyncore.dispatcher.__init__(self)        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)        self.bind(address)        self.listen(1)        self.remote_clients = []    def handle_accept(self):        socket, addr = self.accept() # For the remote client.        self.log.info('Accepted client at %s', addr)        self.remote_clients.append(RemoteClient(self, socket, addr))    def handle_read(self):        self.log.info('Received message: %s', self.read())    def broadcast(self, message):        self.log.info('Broadcasting message: %s', message)        for remote_client in self.remote_clients: remote_client.say(message)class Client(asyncore.dispatcher):    def __init__(self, host_address, name):        asyncore.dispatcher.__init__(self)        self.log = logging.getLogger('Client (%7s)' % name)        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)        self.name = name        self.log.info('Connecting to host at %s', host_address)        self.connect(host_address)        self.outbox = collections.deque()    def say(self, message):        self.outbox.append(message)        self.log.info('Enqueued message: %s', message)    def handle_write(self):        if not self.outbox: return        message = self.outbox.popleft()        if len(message) > MAX_MESSAGE_LENGTH: raise ValueError('Message too long')        self.send(message)    def handle_read(self):        message = self.recv(MAX_MESSAGE_LENGTH)        self.log.info('Received message: %s', message)if __name__ == '__main__':    logging.basicConfig(level=logging.INFO)    logging.info('Creating host')    host = Host()    logging.info('Creating clients')    alice = Client(host.getsockname(), 'Alice')    bob = Client(host.getsockname(), 'Bob')    alice.say('Hello, everybody!')    logging.info('Looping')    asyncore.loop()

结果如下:

INFO:root:Creating hostINFO:root:Creating clientsINFO:Client (  Alice):Connecting to host at ('127.0.0.1', 51117)INFO:Client (    Bob):Connecting to host at ('127.0.0.1', 51117)INFO:Client (  Alice):Enqueued message: Hello, everybody!INFO:root:LoopingINFO:Host:Accepted client at ('127.0.0.1', 55628)INFO:Host:Accepted client at ('127.0.0.1', 55629)INFO:Host:Broadcasting message: Hello, everybody!INFO:Client (  Alice):Received message: Hello, everybody!INFO:Client (    Bob):Received message: Hello, everybody!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号