Python/JavaScript 利用 WebSocket 通信

2019年1月8日


# Python # JavaScript # WebSocket # HTML

Python 中使用 websocket-client

https://github.com/websocket-client/websocket-client

安装

pip install websocket-client

长连接例子

import websocket
try:
    import thread
except ImportError:
    import _thread as 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(3):
            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()

短连接例子

from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()

按键终止 Python 脚本运行

import signal

def quit(signum, frame):
    print 'You stop it.'
    exit()
    # os.exit()
    # sys.exit()


def main():
    signal.signal(signal.SIGINT, quit)
    signal.signal(signal.SIGTERM, quit)
    while True:
        try:
            # my code
        except:
            pass

if __name__ =="__main__":
    #Run as main program
    main()

print("结束循环")

JavaScript 操作 WebSocket

<script>

    var chatSocket = new WebSocket(ws://localhost/sample-url/);

    chatSocket.onmessage = function(e) {
        console.log(e.data)
    };

    chatSocket.onopen = function(e) {
        console.log("已建立连接")
    };

    chatSocket.onclose = function(e) {
        console.error('连接中断');
    };

</script>