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 websockettry: import threadexcept ImportError: import _thread as threadimport timedef 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 websocketfrom threading import Threadimport timeimport sysclass 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 closedself.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_connectionws = 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長連接心跳與短連接的示例的詳細(xì)內(nèi)容,更多關(guān)于Python WebSocket連接的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 專家預(yù)言:PHP將比Java更好更受歡迎2. php設(shè)計模式之模板模式實例分析【星際爭霸游戲案例】3. 詳解php如何合并身份證正反面圖片為一張圖片4. java使用FFmpeg合成視頻和音頻并獲取視頻中的音頻等操作(實例代碼詳解)5. AJAX實現(xiàn)省市縣三級聯(lián)動效果6. Spring @Primary和@Qualifier注解原理解析7. 詳解springBoot啟動時找不到或無法加載主類解決辦法8. ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解9. Java基于redis和mysql實現(xiàn)簡單的秒殺(附demo)10. SpringBoot+SpringCache實現(xiàn)兩級緩存(Redis+Caffeine)
