amitu-websocket-client icon indicating copy to clipboard operation
amitu-websocket-client copied to clipboard

Threaded Version

Open grevian opened this issue 13 years ago • 1 comments

I was having a hard time integrating this into a project where I need to send messages over socket.io, but couldn't allow WebSocket to take over execution of my process, So I extended your classes into a threaded version that can be more easily integrated into my existing code, I'm not sure if you think this is useful but I thought I'd send it your way just in case.

I'm relatively new to Python, and it could be that this is unnecessary and I'm just using your code wrong, but this "WorksForMe™", I'm mildly concerned about thread safety and haven't yet bothered to do much testing, I think the biggest concern would be in user code when a new .on(...) is called before a previous one has finished, in that case I think it's up to the end user to appropriately use locks & semaphors I guess.

The only bug I'm currently experiencing is a long timeout (about 5 seconds) if stop is called after some messages have been sent, before the thread actually terminates

Below is an example of how I'm using it.

from amitu.socketio_client import SocketIOClient
import time

sock = SocketIOClient("localhost", 8001)

def my_func(data):
        sock.emit("recieved it!", { } )

sock.on("call it", my_func)

class TimeoutException(Exception):
        pass

if __name__ == '__main__':
        print "Initializing Messager"
        sock.start()
        wait = 0
        while sock.ready() != True:
                if wait > 100:
                        sock.stop()
                        raise TimeoutException("Websocket timed out while connecting")
                wait += 1
                time.sleep(0.1)
        sock.emit("message", { 'content': 'Initial Message'})
        print "Pausing Main Execution for 5 seconds"
        time.sleep(5)
        sock.emit("message", { 'content': 'Second Message'})
        print "Terminating Program."
        sock.stop()

grevian avatar Dec 26 '11 07:12 grevian

I have just checked in a threaded version of WebSocket. See if that is of any help in your patch.

PS: I still do not know how to correctly terminate the connection, any clues?

amitu avatar Jan 08 '12 20:01 amitu