【Python】websocketクライアントの実装
やっつけ。
環境
前提
- websocket-clientパッケージをインストールしていること
websocket-client 0.35.0 : Python Package Index
Type “python setup.py install” or “pip install websocket-client” to install.
自分はpipでインストールしました。
- 別途websocketサーバがあること
ソース
wsclient.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import websocket import thread import time def on_message(ws, message): print "debug: called on_message" print message def on_error(ws, error): print "debug: called on_error" print error def on_close(ws): print "### closed ###" def on_open(ws): def run(*args): print("debug: websocket is opened") while(True): line = sys.stdin.readline() if line != "": print "debug: sending value is " + line ws.send(line) thread.start_new_thread(run, ()) if __name__ == "__main__": param = sys.argv url = "デフォルトの接続先"; if len(param) == 2: url = param[1] print "debug: param[1] is " + param[1] websocket.enableTrace(True) ws = websocket.WebSocketApp(url, on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
使い方
スクリプトとして実行することを想定しています。
接続
ターミナルを開いて上記ファイルを実行
$ ./wsclient.py
接続先に誤りがなければ、以下のようにハンドシェイクのリクエストとレスポンスが帰ってきます。
正常
--- request header --- GET /hoge HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: example.com:443 Origin: http://example.com Sec-WebSocket-Key: JOtIu/5xaswrI2a5IRh/Wg== Sec-WebSocket-Version: 13 ----------------------- --- response header --- HTTP/1.1 101 Switching Protocols Connection: Upgrade Sec-WebSocket-Accept: CjFvo17ay0vliMi8Pdgm8Ve7LME= Upgrade: WebSocket ----------------------- debug: websocket is opened
接続先に誤りがある場合は以下のようになります。
接続先に誤りがある場合
$ ./wsclient.py ほげ debug: param[1] is ほげ debug: called on_error url is invalid
ちなみにスクリプトの第一引数にURLを渡せるようにしてあります。渡さない場合はソースに直書きしてあるURLをデフォルトの接続先として接続するようになってます。
メッセージ送信
標準入力からメッセージを投げることができます。
適当にタイプして、エンターを叩くとタイプされたテキストをサーバに送信します。
ターミナル
--- response header --- HTTP/1.1 101 Switching Protocols Connection: Upgrade Sec-WebSocket-Accept: CjFvo17ay0vliMi8Pdgm8Ve7LME= Upgrade: WebSocket ----------------------- debug: websocket is opened this is test message debug: sending value is this is test message send: '\x81\x95J\x0c5\xad>d\\\xdejeF\x8d>iF\xd9jaP\xde9mR\xc8@' hoge debug: sending value is hoge send: '\x81\x85\x9f"[\xea\xf7M<\x8f\x95'
分かりにくいですが、「this is test message」と「hoge」が入力した文字です。
使い道
あるのかな? 笑
自分はサクッとサーバのレスポンスをテストしたかったので作ってみました。
参考
websocket-client 0.35.0 : Python Package Index
Pythonで学ぶ 基礎からのプログラミング入門 (8) ユーザーからプログラムへの入力をする方法 | マイナビニュース