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

5

119

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.

Stelle answered 29/6, 2010 at 16:28 Comment(3)
Try Autobahn? tavendo.de/autobahnEffable
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.Duna
You can also try websockets if you are using FastAPICampman
L
218

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()
Lewie answered 19/6, 2012 at 16:45 Comment(7)
@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 ActivePythonArianearianie
@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) !!!Buonarroti
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)Blowfly
@KanwalPrakashSingh Did you solve the client disconnection problem?Olecranon
Geez, don't use sudo. Use --user.Harberd
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...Body
Unless you are on windows, this has a problem handling big messages. Go with @chrisallick suggestionDeactivate
M
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()
Mendiola answered 18/1, 2012 at 17:1 Comment(5)
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?Huey
hey, @Huey 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 :)Mendiola
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS is the correct import for newer versions of autobahn. #21381954Pd
It is probably good to explain what the code is doing if you are going to introduce a new API.Magbie
will it support wss ?Bandstand
T
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).

Testicle answered 9/1, 2012 at 13:19 Comment(2)
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.Duna
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.Testicle
S
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.
Snip answered 4/1, 2011 at 15:15 Comment(4)
but i need a web sobcket in python without tornadoStelle
@Snip Item number 3 is not valid as it's not a WebSocket client, but rather a WebSocket server.Oistrakh
@ZoranPavlovic look at: tornadoweb.org/en/stable/websocket.html it has a WebSocket client implementation.Snip
@Snip 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.Oistrakh
M
-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

Murry answered 4/1, 2011 at 16:31 Comment(1)
videos are a poor vehicle for explaining things like this, please consider posting to html-based documentation or tutorials.Skidproof

© 2022 - 2024 — McMap. All rights reserved.