为什么我无法连接到这个 websocket? [英] Why can't I connect to this websocket?
问题描述
在尝试连接到 Coinfloor 的 websocket API 后,很难获得响应,甚至是令人放心的错误响应.文档在这里:https://github.com/coinfloor/API/blob/master/WEBSOCKET-README.md
Having great difficulty getting a response, even a reassuring error response, after attempts to connect to Coinfloor's websocket API. Docs here: https://github.com/coinfloor/API/blob/master/WEBSOCKET-README.md
'命令、回复和通知以文本形式遍历WebSocket具有 JSON 格式有效负载的帧.'
'Commands, replies, and notifications traverse the WebSocket in text frames with JSON-formatted payloads.'
这是我的尝试:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = 'api.coinfloor.co.uk'
port = 443
server_ip = socket.gethostbyname('api.coinfloor.co.uk')
payload = '{"method": "WatchTicker","base": int("0xF800", 16),"counter":int("0xFA20",16),"watch":True}'
s.connect((server_ip, port))
s.sendall(payload.encode('utf-8'))
result = s.recv(4096)
print(result)
它只是返回这个:
b''
即一个空字节串.
推荐答案
因为套接字和 WebSocket 是完全不同的东西.AF_INET/SOCK_STREAM 套接字是一种使用 TCP 与远程对等方通信的工具.另一方面,WebSocket 是一个二进制协议,
Because sockets and WebSocket are completely different things. AF_INET/SOCK_STREAM socket is a facility that uses TCP to communicate to the remote peer. On the other hand, WebSocket is a binary protocol that
在 TCP 或 TLS 之上工作.
Works on the top of TCP or TLS.
必须在数据交换之前执行 HTTP 握手.
Has to perform HTTP handshake before data exchange.
由于 WebSocket 是一个相当复杂的协议(查看标准),您最好的课程行动是找到一个WebSocket库并使用它,而不是试图实现从TCP开始的协议.
Since WebSocket is a rather complex protocol (see the standard), your best course of action is to find a WebSocket library and use it instead of trying to implement the protocol starting from TCP.
这篇关于为什么我无法连接到这个 websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!