【问题标题】:Python broadcasting message to all clients in a socketPython 向套接字中的所有客户端广播消息
【发布时间】:2014-10-14 21:53:40
【问题描述】:

我使用如下线程制作了一个简单的聊天服务器:

#-*- coding:utf-8 -*-

import _thread as thread
import time
import socket
def now():
    return time.asctime(time.localtime())

def handleclient(connection, ADDR):
    sod = str(ADDR)
    msg = sod+"joined the chat"
    msg2 = msg.encode("utf-8")
    connection.sendall(msg2)
    while True:

        recieved = connection.recv(1024)
        adsf = recieved.decode("utf-8")

        print(now(),"(%s):%s" % (ADDR, recieved))
        output = "%s:%s"%(ADDR, recieved.decode("utf-8"))
        message = output.encode("utf-8")
        connection.sendall(message)




if __name__ == "__main__":
    addr = ("", 8080)
    r =socket.socket()
    print("socket object created at", now())
    r.bind(addr)
    r.listen(5)

    while True:
        print("Waiting for clients...")
        connection, ADDR = r.accept()
        print("We have connection from ", ADDR)

        thread.start_new_thread(handleclient, (connection, ADDR))

但是,sendall 似乎不起作用,并且仅将消息发送给发送它的人。我怎样才能让它发送给所有客户?

【问题讨论】:

  • 这不是sendall() 所做的。你被它的名字弄糊涂了。
  • @Ashwini Chaudhary 哦。它完全与我想要做的不同。有什么解决办法吗?
  • 您必须在此处、列表或字典中跟踪连接对象,并在连接丢失后将其删除。但这会很棘手,因为涉及线程。这就是说我个人更喜欢Twisted 在套接字方面,与线程方式相比,它更易于使用和维护。 Twisted 中的简单聊天服务器示例:twistedmatrix.com/documents/12.3.0/core/examples/chatserver.py
  • 看起来我的线程、解决方案、代码here 可能会有所帮助。

标签: python sockets


【解决方案1】:

没有什么比得上你想要做的了,因为正如赞扬中指出的那样,sendall() 的意思是“肯定发送我所有的字节并继续尝试直到你有”,而不是“将这些字节发送给很多客户。”

您将希望使用 UDP 多播(如果您位于支持它的相对可靠的网络上,例如 LAN 或公司 WAN),或者您只需要显式发送到每个连接的客户端。另一种选择是点对点:发送给多个客户端并指示这些客户端发送给更多客户端,直到所有客户端都得到处理。显然这需要更多的编码。 :)

【讨论】:

    【解决方案2】:

    您可以查看Zero MQ,它通过实现多种模式(发布/订阅、推送/拉取等)在套接字上提供高级设施。

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多