1. 程式人生 > 程式設計 >Python WebSocket長連線心跳與短連線的示例

Python WebSocket長連線心跳與短連線的示例

安裝

pip install websocket-client

先來看一下,長連線呼叫方式:

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()

長連線,引數介紹:

(1)url: websocket的地址。

(2)header: 客戶傳送websocket握手請求的請求頭,{'head1:value1','head2:value2'}。

(3)on_open:在建立Websocket握手時呼叫的可呼叫物件,這個方法只有一個引數,就是該類本身。

(4)on_message:這個物件在接收到伺服器返回的訊息時呼叫。有兩個引數,一個是該類本身,一個是我們從伺服器獲取的字串(utf-8格式)。

(5)on_error:這個物件在遇到錯誤時呼叫,有兩個引數,第一個是該類本身,第二個是異常物件。

(6)on_close:在遇到連線關閉的情況時呼叫,引數只有一個,就是該類本身。

(7)on_cont_message:這個物件在接收到連續幀資料時被呼叫,有三個引數,分別是:類本身,從伺服器接受的字串(utf-8),連續標誌。

(8)on_data:當從伺服器接收到訊息時被呼叫,有四個引數,分別是:該類本身,接收到的字串(utf-8),資料型別,連續標誌。

(9)keep_running:一個二進位制的標誌位,如果為True,這個app的主迴圈將持續執行,預設值為True。

(10)get_mask_key:用於產生一個掩碼。

(11)subprotocols:一組可用的子協議,預設為空。

長連線關鍵方法:ws.run_forever(ping_interval=60,ping_timeout=5)

如果不斷開關閉websocket連線,會一直阻塞下去。另外這個函式帶兩個引數,如果傳的話,啟動心跳包傳送。

ping_interval:自動傳送“ping”命令,每個指定的時間(秒),如果設定為0,則不會自動傳送。

ping_timeout:如果沒有收到pong訊息,則為超時(秒)。

ws.run_forever(ping_interval=60,ping_timeout=5)#ping_interval心跳傳送間隔時間#ping_timeout 設定,傳送ping到收到pong的超時時間

我們看原始碼,會發現這樣一斷程式碼:

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_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長連線心跳與短連線的示例的詳細內容,更多關於Python WebSocket連線的資料請關注我們其它相關文章!