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:

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'

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 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!


Solution 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)

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