主にソケットサーバーにコマンドラインインターフェイスを提供するために、pythonクライアントを接続しようとしているsocket.ioサーバー(node.js内)があります。
私は Python の Web ソケットを使用していますが、これは 4 つの「イベント」しかサポートしていないことに気付きました: オープン時、クローズ時、エラー時、メッセージ時です。
私の socket.io サーバーは、 などのカスタム イベントを定義します.on('connection')
。Pythonでそのようなカスタムイベントを発行/受信するにはどうすればよいですか?
これまでの私のスクリプトは、起動して閉じるだけなので、機能しません。import web socket, requests, thread, time host = ' http://socket-url-server.com '
def on_open(ws):
def run(*args):
print 'did connect'
for i in range(3):
time.sleep(1)
result = ws.recv()
print 'received:'
print result
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
print('Connecting to %s' % host)
socket = host.replace('http://', 'ws://')
print socket
websocket.enableTrace(True)
_ws = websocket.WebSocketApp(socket,
on_message = on_message,
on_error = on_error,
on_close = on_close)
_ws.on_open = on_open
_ws.run_forever()
それ以外の場合、どのライブラリ/メソッドを使用する必要がありますか? ハンドシェイクを実行して socket.io サーバー キーを自分で取得した場合、その後、どのようにイベントを発行/受信できますか?
https://pypi.python.org/pypi/socketIO-clientも使用してみましたが、そのドキュメントは非常に貧弱です
以下に次のスクリプトを書きましたが、取得するNo handlers could be found for logger "socketIO_client"
と永遠にハングします。
from socketIO_client import SocketIO, BaseNamespace
class Namespace(BaseNamespace):
def on_connect(self):
print '[Connected]'
socketIO = SocketIO('http://socket-server-url.com', 80, Namespace)
socketIO.wait(seconds=1)