Using a Python client to test Tornado WebSockets

Post to Twitter

In my last article I showed you how to how to use WebSockets in a very minimal code fashion using Tornado and Python. Today, I’ll show you a very easy way to build a Python client and test out your WebSocket projects using a library called: websocket-client.


To install the websocket-client simply do the following:

$ pip install websocket-client

You also will need Tornado:

$ pip install tornado

If you haven’t worked through my previous article anyou may want to get that project up and running first to see how the basics work. We are going to borrow the code from the ws_app.py file which is listed below and modified for this article:

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
 
 
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        pass
 
    def on_message(self, message):
        self.write_message(u"Your message was: " + message)
 
    def on_close(self):
        pass
 
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/websocket', WebSocketHandler)
        ]

        tornado.web.Application.__init__(self, handlers)
 
 
if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

Note: I removed the handler for the index.html portion of the project, you don’t need to remove this but I’m going to keep the code small and only relvant to what I’m trying to demonstrate.

With almost no modification we can use one of the example files for the websocket-client project. Below is the modified version of the example file:

import websocket

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.create_connection("ws://127.0.0.1:8080/websocket")
    print("Sending 'Hello, World'...")
    ws.send("Hello, World")
    print("Sent")
    print("Receiving...")
    result = ws.recv()
    print("Received {}".format(result))
    ws.close()

Output:

--- request header ---
GET /websocket HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:8080
Origin: http://127.0.0.1:8080
Sec-WebSocket-Key: ZbPfa0XxRI2VFYydS+QkcQ==
Sec-WebSocket-Version: 13

-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: DIzj3H5uGCUCe+EJcGaDN9gfDt8=
-----------------------
Sending 'Hello, World'...
send: ''
Sent
Receiving...
recv: '\x81\x1eYour message was: Hello, World'
Received Your message was: Hello, World
send: ''
recv: '\x88\x00'

If you run each file individually (make sure to start the server portion first) you can see the communication go back and forth. You can see how you can build Python WebSocket clients to test out your WebSocket applications without having to use HTML/JavaScript pages all the time. Sometimes this is all you will need, other times you will need more but its always good to have an extra tool in your belt just in case.

Check out the second example in the websocket-client example folder: echoapp_client.py

Post to Twitter

This entry was posted in Open Source, Python, Tornado. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>