dpallot / simple-websocket-server

A python based websocket server that is simple and easy to use.
951 stars 321 forks source link

Run Web Socket in a separate thread #23

Closed martinsik closed 9 years ago

martinsik commented 9 years ago

Hi, I'm trying to run Web Socket server in another thread while being able to send messages to clients:

clients = []
class SimpleChat(WebSocket):

    def handleMessage(self):
       for client in clients:
          if client != self:
             client.sendMessage(self.address[0] + ' - ' + self.data)

    def handleConnected(self):
       print self.address, 'connected'
       for client in clients:
          client.sendMessage(self.address[0] + u' - connected')
       clients.append(self)

    def handleClose(self):
       clients.remove(self)
       print self.address, 'closed'
       for client in clients:
          client.sendMessage(self.address[0] + u' - disconnected')

def run_server():
    server = SimpleWebSocketServer.SimpleWebSocketServer('', 9000, SimpleChat)
    server.serveforever()

t = threading.Thread(target=run_server)
t.start()

while True:
    for client in clients:
        client.sendMessage('ping')
    time.sleep(1)

It doesn't seem to be sending any messages. Is it because the loop is blocking the main thread? Is there any better way to do it?

dpallot commented 9 years ago

Specify the selectInterval parameter on the init function of SimpleWebSocketServer (maybe 1 sec). If its not set then the blocking select will not be waiting on the descriptor unless the endpoint sends some data. Note that the above code is not thread safe with the current implementation.

martinsik commented 9 years ago

Thanks, selectInterval helped. Can you give me just brief info why is this happening? Is it because the while True loop blocks the main thread instead of SimpleWebSocketServer so messages are queued but never actually sent?

dylancaponi commented 8 years ago

What exactly is selectInterval doing? Why is this not thread safe?