WebSocket broadcast to all clients using Python
Question: 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?


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

