测试Tornado WebSockets

需要 安装这个包websocket-client https://github.com/liris/websocket-client/ 1

pip install websocket-client

tornado 服务器端代码:

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

client 代码

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

运行出现类似下面提示:

--- 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: ur5A7d4CSA+5RK8rZOhPCQ==
Sec-WebSocket-Version: 13

-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: NwuEWqwSAfFcpoBEX9wajFPpJL0=
-----------------------
Sending 'Hello, World'...
send: '\x81\x8c\xbdP1\xdf\xf55]\xb3\xd2|\x11\x88\xd2"]\xbb'
Sent
Receiving...
Received Your message was: Hello, World
send: '\x88\x82\xd3\xf6\x89\xb7\xd0\x1e'

另附参考代码

tornado-websocket-example https://github.com/hiroakis/tornado-websocket-example 2

Relative Articles