WebSocket broadcast to all clients using Python

一世执手 提交于 2019-12-24 03:19:13

问题


I am using a simple Python based web socket application:

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer

class SimpleEcho(WebSocket):

    def handleMessage(self):

        if self.data is None:
            self.data = ''

        # echo message back to client
        self.sendMessage(str(self.data))

    def handleConnected(self):
        print self.address, 'connected'

    def handleClose(self):
        print self.address, 'closed'

server = SimpleWebSocketServer('', 8000, SimpleEcho)
server.serveforever()

It echoes messages sent by each client to the same individual client, but I I am trying to send any message received by the ws server to all clients connected to it. Can someone help me please?


回答1:


Or you could do this:

class SimpleEcho(WebSocket):

    def handleMessage(self):
        if self.data is None:
            self.data = ''

        for client in self.server.connections.itervalues():
            client.sendMessage(str(self.address[0]) + ' - ' + str(self.data))

        #echo message back to client
        #self.sendMessage(str(self.data))

    def handleConnected(self):
        print self.address, 'connected'

    def handleClose(self):
        print self.address, 'closed'



回答2:


I think you want to create a list clients and then progamatically send a message to each of them.

So, when a new client connects, add them to an array:

wss = [] # Should be globally scoped

def handleConnected(self):
    print self.address, 'connected'
    if self not in wss:
        wss.append(self)

Then, when you get a new request, send the message out to each of the clients stored:

def handleMessage(self):
    if self.data is None:
        self.data = ''

    for ws in wss:
        ws.sendMessage(str(self.data))

I hope this helps you!




回答3:


Add this to remove if a client disconnects so the array is not full of not connected people

def handleClose(self):
    wss.remove(self)


来源:https://stackoverflow.com/questions/29871360/websocket-broadcast-to-all-clients-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!