使用Python连接Skinport WebSocket时连接提前终止问题求助
问题分析
从你的控制台输出能看到,WebSocket握手返回了HTTP/1.1 200 OK,而非WebSocket协议要求的101 Switching Protocols,同时响应的Content-Type为text/html——这说明服务器没把你的请求当成WebSocket升级请求处理,而是返回了普通网页内容,所以连接直接关闭,on_message自然不会被触发。
解决步骤
1. 使用正确的WebSocket端点
Skinport的WebSocket服务有专用域名,并非主站域名。正确的端点是:
wss://ws.skinport.com/salefeed
2. 发送符合要求的订阅消息
根据文档,连接建立后需要发送JSON格式的订阅请求,而非随意的"Hello, Server!"。订阅消息格式如下:
{"subscribe": {"appId": 730, "currency": "EUR"}}
修改后的代码
import websocket import json def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws, b, c): print("Connection closed") def on_open(ws): print("Connection opened") # 发送正确的订阅消息 subscribe_msg = json.dumps({"subscribe": {"appId": 730, "currency": "EUR"}}) ws.send(subscribe_msg) if __name__ == "__main__": websocket.enableTrace(True) # 使用正确的WS端点 ws = websocket.WebSocketApp( "wss://ws.skinport.com/salefeed", on_message=on_message, on_error=on_error, on_close=on_close ) ws.on_open = on_open ws.run_forever()
额外说明
- 原代码使用的
wss://skinport.com/saleFeed是主站的HTTP端点,并非WebSocket服务地址,因此服务器返回网页内容导致握手失败。 - 必须发送符合格式的订阅请求,服务器才会开始推送交易消息。
内容的提问来源于stack exchange,提问作者Muhammad Adeel Zahid
相关产品推荐
相关产品推荐

