Skip to content Skip to sidebar Skip to footer

Websocket Broadcast To All Clients Using Python

I am using a simple Python based web socket application: from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer class SimpleEcho(WebSocket): def handleMessage(sel

Solution 1:

Or you could do this:

classSimpleEcho(WebSocket):

    defhandleMessage(self):
        if self.data isNone:
            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))defhandleConnected(self):
        print self.address, 'connected'defhandleClose(self):
        print self.address, 'closed'

Solution 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 scopeddefhandleConnected(self):
    print self.address, 'connected'if self notin wss:
        wss.append(self)

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

defhandleMessage(self):
    if self.data isNone:
        self.data = ''for ws in wss:
        ws.sendMessage(str(self.data))

I hope this helps you!

Solution 3:

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

defhandleClose(self):
    wss.remove(self)

Post a Comment for "Websocket Broadcast To All Clients Using Python"