124

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.

3
  • 2
    Try Autobahn? tavendo.de/autobahn Commented Jan 10, 2012 at 8: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. metajack.im/2008/09/04/… You can thus have Autobahn for WebSockets + XMPP running on one Twisted instance. Disclaimer: I am the author of Autobahn. Commented Jan 31, 2012 at 19:21
  • You can also try websockets if you are using FastAPI Commented Nov 23, 2022 at 16:04

5 Answers 5

222

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()
Sign up to request clarification or add additional context in comments.

5 Comments

@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
@KanwalPrakashSingh Did you solve the client disconnection problem?
Geez, don't use sudo. Use --user.
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...
Unless you are on windows, this has a problem handling big messages. Go with @chrisallick suggestion
24

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

3 Comments

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?
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 :)
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS is the correct import for newer versions of autobahn. stackoverflow.com/questions/21381454/…
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).

2 Comments

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

4 Comments

but i need a web sobcket in python without tornado
@sw. Item number 3 is not valid as it's not a WebSocket client, but rather a WebSocket server.
@ZoranPavlovic look at: tornadoweb.org/en/stable/websocket.html it has a WebSocket client implementation.
@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.
-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 Comment

videos are a poor vehicle for explaining things like this, please consider posting to html-based documentation or tutorials.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.