websocket python實現原理


""" pip install ws4py """
import json
from ws4py.client.threadedclient import WebSocketClient
 
 
class CG_Client(WebSocketClient):
 
    def opened(self):
        req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'
        self.send(req)
 
    def closed(self, code, reason=None):
        print("Closed down:", code, reason)
 
    def received_message(self, resp):
        resp = json.loads(str(resp))
        data = resp['data']
        if type(data) is dict:
            ask = data['asks'][0]
            print('Ask:', ask)
            bid = data['bids'][0]
            print('Bid:', bid)
 
 
if __name__ == '__main__':
    ws = None
    try:
        ws = CG_Client('wss://i.cg.net/wi/ws')
        ws.connect()
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()

  下面介紹另一個比較通用的方法實現websocket:

requirements.txt

websocket_client==0.56.0
six==1.12.0

pip install --no-index --ignore-installed  --find-links=./dependency   -r   requirements.txt
pip download -d ./dependency -r requirements.txt

# coding=utf-8
import ssl
url="localhost:8016/official-website-backend/websocket?"
import wave,os
p="2019-05-06_11-42-06_8611.wav"
path=os.path.join(os.getcwd(),p)
files=wave.open(path,'rb')
data=files.readframes(1024)
print("data type is %s"%type(data))
import json
import websocket



def on_message(ws, message): # 服務器有數據更新時,主動推送過來的數據
print(message)


def on_error(ws, error): # 程序報錯時,就會觸發on_error事件
print(error)


def on_close(ws):
print("Connection closed ……")


def on_open(ws): # 連接到服務器之后就會觸發on_open事件,這里用於send數據
req=data
print("發送文件type: %s"%type(data))
ws.send(req)


if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp(url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.on_message=on_message
ws.on_error=on_error
ws.on_close=on_close
ws.run_forever(ping_timeout=30)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM