102

I found this project: http://code.google.com/p/standalonewebsocketserver/ 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.

Mateusz Piotrowski
  • 6,087
  • 9
  • 44
  • 71
diegueus9
  • 20,833
  • 15
  • 58
  • 73
  • 2
    Try Autobahn? http://www.tavendo.de/autobahn/ – Len Holgate Jan 10 '12 at 08:16
  • 3
    Since Autobahn is based on Twisted, it may be also worth noting that Twisted has very good support for XMPP as well, i.e. http://metajack.im/2008/09/04/get-twisted-on-xmpp---the-future-of-twisted-words/ You can thus have Autobahn for WebSockets + XMPP running on one Twisted instance. Disclaimer: I am the author of Autobahn. – oberstet Jan 31 '12 at 19:21

5 Answers5

174

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

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://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()
ChrisCantrell
  • 3,553
  • 1
  • 18
  • 14
Bryan Hunt
  • 3,265
  • 2
  • 22
  • 34
  • 4
    @SSHThis `pip install` works fine on windows! I'm using ActivePython 2.7 and ran `pip install websocket-client` and it just worked. The only issue was that `python` clashed with cygwin python, so I had to explicitly run `/cygdrive/C/Python27/python` to get ActivePython – Mark Lakata Dec 12 '13 at 00:35
  • @bryan hunt how to handle the case when the server disconnects, as in i get broken pipe errors - writing to a closed pipe/socket/fd (probably the client disconnected) !!! – Kanwal Prakash Singh Apr 20 '16 at 08:54
  • How do I pass the url in commandline when running. for example if I need to give the url of ws ("ws://localhost:8080/websocket") in commandline .. ws = create_connection("ws://localhost:8080/websocket").. like ws = create_connection(sys.argv) – Soundarya Thiagarajan Aug 23 '16 at 06:21
  • 1
    @KanwalPrakashSingh Did you solve the client disconnection problem? – Jey Sep 16 '16 at 14:17
  • Geez, don't use `sudo`. Use `--user`. – Perfi Jun 07 '18 at 10:09
  • Hey! The sample server code you mentioned, isn't is the example of long_connection according to the documentation? I want to call a websocket bur I am really confused what is this two method represents... – Mohammad Tayyab Dec 03 '18 at 00:09
  • Unless you are on windows, this has a problem handling big messages. Go with @chrisallick suggestion – Gouz Aug 01 '20 at 19:06
23

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 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()
chrisallick
  • 1,269
  • 14
  • 18
  • hey chris, do you know how can one disconnect a client forcefully from server side using this autobahn websocket server?? which function do i have to call to do that? – Johnydep Sep 08 '12 at 21:13
  • hey, @Johnydep yeah, i believe it's part of the spec that both participants in a websocket connection can initiate a "close." Don't quote me though. Anyways, I looked at the source code and there is: "dropConnection" and "sendClose" i'd just plug them in and test them :) – chrisallick Oct 15 '12 at 20:52
  • 2
    `from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS` is the correct import for newer versions of autobahn. http://stackoverflow.com/questions/21381454/autobahn-cannot-import-name-error – evan54 Oct 24 '15 at 21:58
  • 1
    It is probably good to explain what the code is doing if you are going to introduce a new API. – user650261 Nov 19 '15 at 00:26
  • 1
    will it support wss ? – Arun Jan 17 '19 at 09:25
10

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).

kiddouk
  • 2,303
  • 2
  • 14
  • 19
  • 1
    Regarding concurrency: we have tested Autobahn client up to 60k WS outgoing connections and Autobahn server up to incoming 180k WS connections. On Windows, this was tested using Twisted running IOCP (IO Completion Ports) reactor and on FreeBSD this was tested using kqueue reactor. Disclaimer: I'm the author of Autobahn. – oberstet Jan 31 '12 at 19:15
  • 1
    Talking about numbers, on my side, I have made some extended tests with Tornado Websocket (and WS-for-py) and I easily get 15k connections. Not as much but good for a test anyway. – kiddouk Feb 02 '12 at 07:55
0
  1. Take a look at the echo client under http://code.google.com/p/pywebsocket/ It's a Google project.
  2. A good search in github is: https://github.com/search?type=Everything&language=python&q=websocket&repo=&langOverride=&x=14&y=29&start_value=1 it returns clients and servers.
  3. 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.
sw.
  • 3,136
  • 2
  • 29
  • 41
  • 1
    but i need a web sobcket in python without tornado – diegueus9 Jan 04 '11 at 16:10
  • @sw. Item number 3 is not valid as it's not a WebSocket client, but rather a WebSocket server. – Zoran Pavlovic Mar 20 '14 at 19:26
  • @ZoranPavlovic look at: http://www.tornadoweb.org/en/stable/websocket.html it has a WebSocket client implementation. – sw. Mar 21 '14 at 18:55
  • @sw. Yes, but the link in point 3 is to a python server and javascript client. You should update it with the new url you just posted, and thanks for the find! It's exactly what I was looking for. – Zoran Pavlovic Mar 21 '14 at 20:27
-1

web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653

  • 1
    videos are a poor vehicle for explaining things like this, please consider posting to html-based documentation or tutorials. – Chris Withers Nov 13 '18 at 19:15