2019-03-18

python? stomp訂閱websocket

這兩天被這個(gè)搞的頭大,一般的訂閱websocket都是沒問題的,這個(gè)用的是stomp,這下之前訂閱的方法就不行了,查了很多資料,都很少有關(guān)于這方面的資料;

一直在stomp模塊上下功夫,但是這個(gè)模塊連接的時(shí)候要ip和端口,不靠譜,怎么都連不上的,用stomp的代碼如下,可以看到connection這里要ip和端口:

import stomp

class MyListener(object):

? ? def on_error(self, headers, message):

? ? ? ? print('received an error %s' % message)

? ? def on_message(self, headers, message):

? ? ? ? print('received a message %s' % message)

conn = stomp.Connection([('115.28.253.107', 61613)])

conn.set_listener('', MyListener())

conn.start()

conn.connect('geust', 'guest', wait=True)

conn.send(body='SUBSCRIBE', destination='/WALEOS@depth40')

conn.subscribe(destination='/WALEOS@depth40', id='sub-0', ack='auto')

conn.disconnect()


? 其實(shí)也想用node連,腳本都寫好了數(shù)據(jù)也能拿到,奈何對node了解不多,對數(shù)據(jù)處理都沒操作過,還有部署,最終還是放棄了;

? 最后無意中用google搜了下看到一個(gè)人用stomper,而且用的正常的訂閱,貌似找到了希望,趕緊操作一波,可以獲得數(shù)據(jù),搞定,代碼如下:

import stomper

import ssl

import random

import time

from websocket import create_connection

url ='wss://w.whaleex.com.cn/ws/websocket'

ws = create_connection(url, sslopt={"cert_reqs": ssl.CERT_NONE})

v =str(random.randint(0, 1000))

sub = stomper.subscribe("/WALEOS@depth10", v, ack='auto')

sub_plus = stomper.send("/WALEOS@depth10", '')

ws.send(sub)

ws.send(sub_plus)

sub1 = stomper.subscribe("/WALEOS@trade", v, ack='auto')

sub2 = stomper.send("/WALEOS@trade", '')

ws.send(sub1)

ws.send(sub2)

l = [sub2, sub_plus]

while True:

? ? for i in l:

? ? ? ? content = ws.recv()

? ? ? ? if 'symbol' in content:

? ? ? ? ? ? print('======', content, '\n=======')

? ? ? ? ? ? continue

? ? ? ? print('--->', content, '\n+-------+')

? ? ? ? ws.send(i)

? ? ? ? time.sleep(1)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容