Python WebSocket長連接心跳與短連接的示例
安裝
pip install websocket-client
先來看一下,長連接調(diào)用方式:
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()
長連接,參數(shù)介紹:
(1)url: websocket的地址。
(2)header: 客戶發(fā)送websocket握手請求的請求頭,{'head1:value1','head2:value2'}。
(3)on_open:在建立Websocket握手時調(diào)用的可調(diào)用對象,這個方法只有一個參數(shù),就是該類本身。
(4)on_message:這個對象在接收到服務(wù)器返回的消息時調(diào)用。有兩個參數(shù),一個是該類本身,一個是我們從服務(wù)器獲取的字符串(utf-8格式)。
(5)on_error:這個對象在遇到錯誤時調(diào)用,有兩個參數(shù),第一個是該類本身,第二個是異常對象。
(6)on_close:在遇到連接關(guān)閉的情況時調(diào)用,參數(shù)只有一個,就是該類本身。
(7)on_cont_message:這個對象在接收到連續(xù)幀數(shù)據(jù)時被調(diào)用,有三個參數(shù),分別是:類本身,從服務(wù)器接受的字符串(utf-8),連續(xù)標(biāo)志。
(8)on_data:當(dāng)從服務(wù)器接收到消息時被調(diào)用,有四個參數(shù),分別是:該類本身,接收到的字符串(utf-8),數(shù)據(jù)類型,連續(xù)標(biāo)志。
(9)keep_running:一個二進制的標(biāo)志位,如果為True,這個app的主循環(huán)將持續(xù)運行,默認(rèn)值為True。
(10)get_mask_key:用于產(chǎn)生一個掩碼。
(11)subprotocols:一組可用的子協(xié)議,默認(rèn)為空。
長連接關(guān)鍵方法:ws.run_forever(ping_interval=60,ping_timeout=5)
如果不斷開關(guān)閉websocket連接,會一直阻塞下去。另外這個函數(shù)帶兩個參數(shù),如果傳的話,啟動心跳包發(fā)送。
ping_interval:自動發(fā)送“ping”命令,每個指定的時間(秒),如果設(shè)置為0,則不會自動發(fā)送。
ping_timeout:如果沒有收到pong消息,則為超時(秒)。
ws.run_forever(ping_interval=60,ping_timeout=5)#ping_interval心跳發(fā)送間隔時間#ping_timeout 設(shè)置,發(fā)送ping到收到pong的超時時間
我們看源代碼,會發(fā)現(xiàn)這樣一斷代碼:
ping的超時時間,要大于ping間隔時間
if not ping_timeout or ping_timeout <= 0: ping_timeout = None if ping_timeout and ping_interval and ping_interval <= ping_timeout: raise WebSocketException("Ensure ping_interval > ping_timeout")
長連接:
示例1:
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): ws.send("hello1") time.sleep(1) ws.close() 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(ping_interval=60,ping_timeout=5)
示例2:
import websocket from threading import Thread import time import sys class MyApp(websocket.WebSocketApp): def on_message(self, message): print(message) def on_error(self, error): print(error) def on_close(self): print("### closed ###") def on_open(self): def run(*args): for i in range(3): # send the message, then wait # so thread doesn't exit and socket # isn't closed self.send("Hello %d" % i) time.sleep(1) time.sleep(1) self.close() print("Thread terminating...") Thread(target=run).start() if __name__ == "__main__": websocket.enableTrace(True) if len(sys.argv) < 2: host = "ws://echo.websocket.org/" else: host = sys.argv[1] ws = MyApp(host) 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 WebSocket長連接心跳與短連接的示例的詳細內(nèi)容,更多關(guān)于Python WebSocket連接的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
調(diào)試Python程序代碼的幾種方法總結(jié)
這篇文章主要介紹了調(diào)試Python程序代碼的幾種方法總結(jié),文中代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04使用Python編程分析火爆全網(wǎng)的魷魚游戲豆瓣影評
本文來為大家介紹如何使用Python爬取影評的操作,主要是爬取《魷魚游戲》在豆瓣上的一些影評,對數(shù)據(jù)做一些簡單的分析,用數(shù)據(jù)的角度重新審視下這部劇,有需要的朋友可以借鑒參考下2021-10-10linux系統(tǒng)使用python監(jiān)測網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出
這篇文章主要介紹了linux系統(tǒng)使用python監(jiān)測網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出信息,大家參考使用吧2014-01-01django 多數(shù)據(jù)庫及分庫實現(xiàn)方式
這篇文章主要介紹了django 多數(shù)據(jù)庫及分庫實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04