Search code examples
pythonwebsocketstreamchatbroadcast

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(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?


Solution

  • 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'