WildWombat
WildWombat

Reputation: 416

Can't connect to the Binance websocket with Socket.io

I'm using NodeJS and trying to connect to the Binance Websocket with Socket.io but it seems to not work, but when I try it with the standard "ws" library, it works fine and I'm trying to figure out what I'm doing wrong. These are the docs if needed.

Here's my code with Socket.io

const io = require("socket.io-client");
const socket = io("wss://stream.binance.com:9443/ws/btcusdt@trade");

console.log("Starting...");

socket.on("connect", () => {
    console.log("Connection Made!"); //This never fires
});
socket.on("message", (data) => {
    console.log(data);
});

Here's my code with the "ws" library

const ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");

ws.on("message", function incoming(data) {
    console.log(data);
});

Which works fine.

Any ideas?

Upvotes: 1

Views: 2213

Answers (1)

LI HO TAN
LI HO TAN

Reputation: 133

According to https://socket.io/docs/v4/#What-Socket-IO-is-not .

What Socket.IO is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.

// WARNING: the client will NOT be able to connect!
const socket = io("ws://echo.websocket.org");

If you are looking for a plain WebSocket server, please take a look at ws or uWebSockets.js.

There are also talks to include a WebSocket server in the Node.js core.

On the client-side, you might be interested by the robust-websocket package.

Upvotes: 3

Related Questions