jsstuball
jsstuball

Reputation: 4951

Why can't I connect to this websocket?

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

'Commands, replies, and notifications traverse the WebSocket in text frames with JSON-formatted payloads.'

Here is my attempt:

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)

It just returns this:

b'' 

i.e. an empty byte string.

Upvotes: 0

Views: 170

Answers (1)

u354356007
u354356007

Reputation: 3225

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

  1. Works on the top of TCP or TLS.

  2. Has to perform HTTP handshake before data exchange.

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.

Upvotes: 2

Related Questions