Python socketIO-client 运行代码不返回信息的原因是什么?
""" An example for Python Socket.io Client
Requires: six,socketIO_client
"""
from socketIO_client import SocketIO, BaseNamespace
import json
import time
import re
import hmac
import hashlib
import base64
import logging
logging.getLogger(‘socketIO-client’).setLevel(logging.DEBUG)
logging.basicConfig()
access_key = “”
secret_key = “"
def get_tonce():
return int(time.time() * 1000000)
def get_postdata():
post_data = {}
tonce = get_tonce()
post_data[‘tonce’] = tonce
post_data[‘accesskey’] = access_key
post_data[‘requestmethod’] = ‘post’
if 'id' not in post_data:
post_data['id'] = tonce
#modefy here to meet your requirement
post_data['method'] = 'subscribe'
post_data['params'] = ['order_cnybtc', 'order_cnyltc', 'account_info']
return post_data
def get_sign(pdict):
pstring = ‘’
fields = [‘tonce’, ‘accesskey’, ‘requestmethod’, ‘id’, ‘method’, ‘params’]
for f in fields:
if pdict[f]:
if f == ‘params’:
param_string=str(pdict[f])
param_string=param_string.replace(‘None’, ‘’)
param_string=re.sub("[[] ]","",param_string)
param_string=re.sub("’",’’,param_string)
pstring+=f+’=’+param_string+’&’
else:
pstring+=f+’=’+str(pdict[f])+’&’
else:
pstring+=f+’=&’
pstring=pstring.strip(’&’)
phash = hmac.new(secret_key, pstring, hashlib.sha1).hexdigest()
return base64.b64encode(access_key + ':' + phash)
class Namespace(BaseNamespace):
def on_connect(self):
print('[Connected]')
def on_disconnect(self):
print('[Disconnect]')
def on_ticker(self, *args):
print('ticker', args)
def on_trade(self, *args):
print('trade', args)
def on_grouporder(self, *args):
print('grouporder', args)
def on_order(self, *args):
print('order', args)
def on_account_info(self, *args):
print('account_info', args)
def on_message(self, *args):
print('message', args)
def on_error(self, data):
print(data)
socketIO = SocketIO(‘https://websocket.btcchina.com’)
namespace = socketIO.define(Namespace)
namespace.emit(‘subscribe’, ‘marketdata_cnybtc’)
namespace.emit(‘subscribe’, ‘marketdata_cnyltc’)
namespace.emit(‘subscribe’, ‘grouporder_cnybtc’)
namespace.emit(‘subscribe’, ‘grouporder_cnyltc’)
payload = get_postdata()
arg = [json.dumps(payload), get_sign(payload)]
namespace.emit(‘private’, arg)
socketIO.wait(seconds=1)
namespace.disconnect()
当我运行 namespace.emit('subscribe', 'marketdata_cnybtc')
namespace.emit('subscribe', 'marketdata_cnyltc')
namespace.emit('subscribe', 'grouporder_cnybtc')
namespace.emit('subscribe', 'grouporder_cnyltc')
这个后,发现根本没有返回东西
/home/daneel/anaconda3/envs/btchina/bin/python /home/daneel/PycharmProjects/btchina/WebsocketClient.py
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [engine.io transport selected] websocket
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [engine.io heartbeat reset]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet sent] 2["subscribe", "marketdata_cnybtc"]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet sent] 2["subscribe", "marketdata_cnyltc"]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet sent] 2["subscribe", "grouporder_cnybtc"]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet sent] 2["subscribe", "grouporder_cnyltc"]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet sent] 2["private", ["{\"accesskey\": \"safadfasafa\", \"id\": 1495691413689407, \"requestmethod\": \"post\", \"tonce\": 1495691413689407, \"params\": [\"order_cnybtc\", \"order_cnyltc\", \"account_info\"], \"method\": \"subscribe\"}", "fdsafdsdafdfafdasfsafasdfas="]]
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io packet received] 0
DEBUG:socketIO-client:websocket.btcchina.com:443/socket.io [socket.io connected]
('message', ('0',))
[Connected]
[Disconnect]
Python socketIO-client 运行代码不返回信息的原因是什么?
这玩意的 py 端有维护过?印象中长期处于不能用状态。
请用 sockjs
这个问题通常是因为事件监听没设置对,或者连接没建立好。socketIO-client需要正确配置事件处理函数才能收到服务端推送的数据。
最常见的原因是:
- 没注册事件监听器
- 连接参数配置错误
- 没启动事件循环
看看这个完整示例:
from socketIO_client import SocketIO, LoggingNamespace
def on_connect():
print('连接成功')
def on_message(data):
print('收到消息:', data)
def on_disconnect():
print('断开连接')
# 创建连接
socketIO = SocketIO('localhost', 8000, LoggingNamespace)
# 注册事件监听
socketIO.on('connect', on_connect)
socketIO.on('message', on_message)
socketIO.on('disconnect', on_disconnect)
# 发送消息测试
socketIO.emit('my_event', {'data': '测试数据'})
# 关键:启动等待循环
socketIO.wait(seconds=10)
如果还是收不到消息,检查服务端是否正常发送事件,以及事件名称是否匹配。
总结:确保事件监听和连接都正确配置。
这玩意的 py 端还一直挺好用的,只是更新缓慢却并没有什么问题
印象中 13、14、15 这几年,一直没有使用成功过,于是就弃了。很久不关注,可能后来修了吧
javascript<br>// install socket.io.js for Javascript client to work<br><script src="/home/daneel/node_modules/<a target="_blank" href="http://socket.io" rel="nofollow noopener">socket.io</a>-client/dist/socket.io.js"></script><br><script><br> var socket = io('<a target="_blank" href="https://websocket.btcchina.com/');" rel="nofollow noopener">https://websocket.btcchina.com/');</a><br> socket.emit('subscribe', ['marketdata_cnybtc']);<br> socket.emit('subscribe', ['marketdata_cnyltc']);<br> socket.on('connect', function(){<br> console.log("Hello,btcc!");<br> socket.on('trade', function (data) {<br> console.log("Hello,trade!");<br> console.log(data);});<br> });<br></script><br>
这段代码就可以用,在火狐浏览器打开后,console 里面会接收 socket server 的信息,但是同样用 Python 的代码就不可以,该怎么解决这个问题呢?可以用 Python 去调用上面的代码么?
还是希望能够指出 python 中哪个地方错了? https://github.com/invisibleroads/socketIO-client
这个是 sockIO_client 的源码
你这里需要循环调用 socketIO.wait,只调用一次他只会处理一个请求就退出了
Wait forever.
from socketIO_client import SocketIO
socketIO = SocketIO(‘localhost’, 8000)
socketIO.wait()
楼上+1, 请使用 socketIO.wait() 把 seconds=1 去掉
另外,请绑定 trade 事件,如:
def on_trade_response():
print(data)
socketIO.on(‘trade’, on_trade_response)
这个库去年到前几天还有 bug
是的,我还发过 pr,在下面有一堆人都要求作者合并,作者也一点反应都没有
还是只提示这个 connect
![image_1bgvs0ejq1eoh6721to0rq6e089.png-45.4kB][1]
[1]: http://static.zybuluo.com/daneel/7zkrqrjj4frno4tu5z939p5q/image_1bgvs0ejq1eoh6721to0rq6e089.png
我都说了,在主线程用
while True:
socketIO.wait()
感谢, 在原先代码中加了
while True:
socketIO_wait()
还是没有返回信息,麻烦再帮我下。

javascript <br>// install socket.io.js for Javascript client to work <br><script src="/home/daneel/node_modules/<a target="_blank" href="http://socket.io" rel="nofollow noopener">socket.io</a>-client/dist/socket.io.js"></script> <br><script> <br>var socket = io('<a target="_blank" href="https://websocket.btcchina.com/');" rel="nofollow noopener">https://websocket.btcchina.com/');</a><br>socket.emit('subscribe', ['marketdata_cnybtc']); <br>socket.emit('subscribe', ['marketdata_cnyltc']); <br>socket.on('connect', function(){ <br>console.log("Hello,btcc!"); <br>socket.on('trade', function (data) { <br>console.log("Hello,trade!"); <br>console.log(data);}); <br>}); <br></script> <br>
人家 emit 的是一个数组,你 emit 一个字符串,当然没有返回了………

改成数组依然不行啊
可以再给点提示么?这个代码里面没有 connect。
你的网页我也跑了一遍,并没有得到什么数据呀,只有最初的 connect 信息
是他服务器的事情么?那段 html 昨天还能运行,然后我在 console 里面能接收数据,结果今天一试啥都不行了。你能告诉我怎么确定服务器没事么?
https://www.btcchina.com/apidocs/spot-exchange-market-data-websocket-api-zh.html 不同版本的代码都在这里,这是比特币中国给的 api,我按照他给的 github 代码,直接运行,就不行。我是想把这个实时数据抓下来,做一些分析。结果就卡在这第一步了。
也有可能是他换接口之类的了
另外 socket.io 支持使用 http session 来做登录验证,而我这里并没有登录,你那里过了一天,可能 session 失效了,可能是必须要先登录才能拿到信息吧
我们订阅的公开的市场信息,那个不需要登录。
楼主你好,我用比特币中国开发者平台上提供的 WebSocket 市场数据 API ( https://www.btcchina.com/apidocs/spot-exchange-market-data-websocket-api-zh.html )上面提供的 Python 版本 Socket.io 客户端示例源代码( https://github.com/BTCChina/btcchina-websocket-api-python )是可以正确运行并且获得返回结果的。我的运行环境是 Python 2.7.13 ( README.md 里面说了 compiled in python 2.7.x ),socket.io client library 使用的是 socketIO-client 0.7.2 ( https://pypi.python.org/pypi/socketIO-client/0.7.2 )。
至于你的代码,我觉得除了 secret_key = “"这行双引号的 Typo 以外,其他地方没有什么问题,和 socketIO.wait(seconds=1)关系不大,并不是“只调用一次他只会处理一个请求就退出了”,只是运行多久的差别。我的运行结果如下:
考虑到是三个多月前的帖子,我估计上去应该是那段时间服务器的问题,所以你肯定已经解决了问题,但是我还是回帖希望可以给你或者以后看到这贴的朋友们提供一些参考和帮助。


