Python WebSocket長(zhǎng)連接心跳與短連接的示例
安裝
pip install websocket-client
先來(lái)看一下,長(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)
如果不斷開(kāi)關(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:如果沒(méi)有收到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 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長(zhǎng)連接心跳與短連接的示例的詳細(xì)內(nèi)容,更多關(guān)于Python WebSocket連接的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Python 聊聊socket中的listen()參數(shù)(數(shù)字)到底代表什么
- Python Socket多線程并發(fā)原理及實(shí)現(xiàn)
- python基于socket模擬實(shí)現(xiàn)ssh遠(yuǎn)程執(zhí)行命令
- Python基于Socket實(shí)現(xiàn)簡(jiǎn)易多人聊天室的示例代碼
- 用Python進(jìn)行websocket接口測(cè)試
- Python使用socket模塊實(shí)現(xiàn)簡(jiǎn)單tcp通信
- python Socket網(wǎng)絡(luò)編程實(shí)現(xiàn)C/S模式和P2P
- Python基礎(chǔ)之Socket通信原理
相關(guān)文章
Python Tensor FLow簡(jiǎn)單使用方法實(shí)例詳解
這篇文章主要介紹了Python Tensor FLow簡(jiǎn)單使用方法,結(jié)合實(shí)例形式詳細(xì)分析了Tensor FLow相關(guān)概念、原理、用法與操作注意事項(xiàng),需要的朋友可以參考下2020-01-01
調(diào)試Python程序代碼的幾種方法總結(jié)
這篇文章主要介紹了調(diào)試Python程序代碼的幾種方法總結(jié),文中代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04
使用Python編程分析火爆全網(wǎng)的魷魚游戲豆瓣影評(píng)
本文來(lái)為大家介紹如何使用Python爬取影評(píng)的操作,主要是爬取《魷魚游戲》在豆瓣上的一些影評(píng),對(duì)數(shù)據(jù)做一些簡(jiǎn)單的分析,用數(shù)據(jù)的角度重新審視下這部劇,有需要的朋友可以借鑒參考下2021-10-10
linux系統(tǒng)使用python監(jiān)測(cè)網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出
這篇文章主要介紹了linux系統(tǒng)使用python監(jiān)測(cè)網(wǎng)絡(luò)接口獲取網(wǎng)絡(luò)的輸入輸出信息,大家參考使用吧2014-01-01
Python 創(chuàng)建守護(hù)進(jìn)程的示例
這篇文章主要介紹了Python 創(chuàng)建守護(hù)進(jìn)程的示例,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-09-09
Python Pandas分組聚合的實(shí)現(xiàn)方法
這篇文章主要介紹了Python Pandas分組聚合的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
django 多數(shù)據(jù)庫(kù)及分庫(kù)實(shí)現(xiàn)方式
這篇文章主要介紹了django 多數(shù)據(jù)庫(kù)及分庫(kù)實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04

