I found this project: for a WebSocket server, but I need to implement a WebSocket client in python, more exactly I need to receive some commands from XMPP in my WebSocket server.
25 Answers
Ridiculously easy to use.
sudo pip install websocket-client Sample client code:
#!/usr/bin/python from websocket import create_connection ws = create_connection("ws://localhost:8080/websocket") print "Sending 'Hello, World'..." ws.send("Hello, World") print "Sent" print "Receiving..." result = ws.recv() print "Received '%s'" % result ws.close() Sample server code:
#!/usr/bin/python import websocket import thread import time def on_message(ws, message): print message def on_error(ws, error): print error def 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://", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever() 7Autobahn 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 reactor from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS class 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() 5Since 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(') 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).
- Take a look at the echo client under It's a Google project.
- A good search in github is: it returns clients and servers.
- Bret Taylor also implemented web sockets over Tornado (Python). His blog post at: Web Sockets in Tornado and a client implementation API is shown at tornado.websocket in the client side support section.
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: and here vimeo . com / 18232653
1