Is there a WebSocket client implemented for Python? [closed] Is there a WebSocket client implemented for Python? [closed] python python

Is there a WebSocket client implemented for Python? [closed]


http://pypi.python.org/pypi/websocket-client/

Ridiculously easy to use.

 sudo pip install websocket-client

Sample client code:

#!/usr/bin/pythonfrom websocket import create_connectionws = create_connection("ws://localhost:8080/websocket")print "Sending 'Hello, World'..."ws.send("Hello, World")print "Sent"print "Receiving..."result =  ws.recv()print "Received '%s'" % resultws.close()

Sample server code:

#!/usr/bin/pythonimport websocketimport threadimport timedef on_message(ws, message):    print messagedef on_error(ws, error):    print errordef on_close(ws):    print "### closed ###"def on_open(ws):    def run(*args):        for i in range(30000):            time.sleep(1)            ws.send("Hello %d" % i)        time.sleep(1)        ws.close()        print "thread terminating..."    thread.start_new_thread(run, ())if __name__ == "__main__":    websocket.enableTrace(True)    ws = websocket.WebSocketApp("ws://echo.websocket.org/",                                on_message = on_message,                                on_error = on_error,                                on_close = on_close)    ws.on_open = on_open    ws.run_forever()


Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactorfrom autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWSclass EchoClientProtocol(WebSocketClientProtocol):   def sendHello(self):      self.sendMessage("Hello, world!")   def onOpen(self):      self.sendHello()   def onMessage(self, msg, binary):      print "Got echo: " + msg      reactor.callLater(1, self.sendHello)if __name__ == '__main__':   factory = WebSocketClientFactory("ws://localhost:9000")   factory.protocol = EchoClientProtocol   connectWS(factory)   reactor.run()


Since I have been doing a bit of research in that field lately (Jan, '12), the most promising client is actually : WebSocket for Python. It support a normal socket that you can call like this :

ws = EchoClient('http://localhost:9000/ws')

The client can be Threaded or based on IOLoop from Tornado project. This will allow you to create a multi concurrent connection client. Useful if you want to run stress tests.

The client also exposes the onmessage, opened and closed methods. (WebSocket style).