Python WebSocket長(zhǎng)連接心跳與短連接的示例
安裝
pip install websocket-client
先來看一下,長(zhǎng)連接調(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()
長(zhǎng)連接,參數(shù)介紹:
(1)url: websocket的地址。
(2)header: 客戶發(fā)送websocket握手請(qǐng)求的請(qǐng)求頭,{’head1:value1’,’head2:value2’}。
(3)on_open:在建立Websocket握手時(shí)調(diào)用的可調(diào)用對(duì)象,這個(gè)方法只有一個(gè)參數(shù),就是該類本身。
(4)on_message:這個(gè)對(duì)象在接收到服務(wù)器返回的消息時(shí)調(diào)用。有兩個(gè)參數(shù),一個(gè)是該類本身,一個(gè)是我們從服務(wù)器獲取的字符串(utf-8格式)。
(5)on_error:這個(gè)對(duì)象在遇到錯(cuò)誤時(shí)調(diào)用,有兩個(gè)參數(shù),第一個(gè)是該類本身,第二個(gè)是異常對(duì)象。
(6)on_close:在遇到連接關(guān)閉的情況時(shí)調(diào)用,參數(shù)只有一個(gè),就是該類本身。
(7)on_cont_message:這個(gè)對(duì)象在接收到連續(xù)幀數(shù)據(jù)時(shí)被調(diào)用,有三個(gè)參數(shù),分別是:類本身,從服務(wù)器接受的字符串(utf-8),連續(xù)標(biāo)志。
(8)on_data:當(dāng)從服務(wù)器接收到消息時(shí)被調(diào)用,有四個(gè)參數(shù),分別是:該類本身,接收到的字符串(utf-8),數(shù)據(jù)類型,連續(xù)標(biāo)志。
(9)keep_running:一個(gè)二進(jìn)制的標(biāo)志位,如果為True,這個(gè)app的主循環(huán)將持續(xù)運(yùn)行,默認(rèn)值為True。
(10)get_mask_key:用于產(chǎn)生一個(gè)掩碼。
(11)subprotocols:一組可用的子協(xié)議,默認(rèn)為空。
長(zhǎng)連接關(guān)鍵方法:ws.run_forever(ping_interval=60,ping_timeout=5)
如果不斷開關(guān)閉websocket連接,會(huì)一直阻塞下去。另外這個(gè)函數(shù)帶兩個(gè)參數(shù),如果傳的話,啟動(dòng)心跳包發(fā)送。
ping_interval:自動(dòng)發(fā)送“ping”命令,每個(gè)指定的時(shí)間(秒),如果設(shè)置為0,則不會(huì)自動(dòng)發(fā)送。
ping_timeout:如果沒有收到pong消息,則為超時(shí)(秒)。
ws.run_forever(ping_interval=60,ping_timeout=5)#ping_interval心跳發(fā)送間隔時(shí)間#ping_timeout 設(shè)置,發(fā)送ping到收到pong的超時(shí)時(shí)間
我們看源代碼,會(huì)發(fā)現(xiàn)這樣一斷代碼:
ping的超時(shí)時(shí)間,要大于ping間隔時(shí)間
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')
長(zhǎng)連接:
示例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長(zhǎng)連接心跳與短連接的示例的詳細(xì)內(nèi)容,更多關(guān)于Python WebSocket連接的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用Python和百度語音識(shí)別生成視頻字幕的實(shí)現(xiàn)2. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法3. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. php中sort函數(shù)排序知識(shí)點(diǎn)總結(jié)6. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?7. css代碼優(yōu)化的12個(gè)技巧8. axios和ajax的區(qū)別點(diǎn)總結(jié)9. xml中的空格之完全解說10. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算
