I’m trying to connect to a WebSocket. The URL looks like this:
wss://xxx.xxx.com/public/time/player/test/xxx/socket?messageFormat=json&SESSIONID=xxx&instance=xxx&client_version=xxx
In JavaScript, it works perfectly, and I receive all messages. However, when I try the same in Node.js, it doesn’t even connect.
I’ve already tried using different packages like websocket
and wb
, but none of them worked.
Here’s the code I used in plain JavaScript:
const socketUrl = 'wss://xxx.xxx.com/public/time/player/test/xxx/socket?messageFormat=json&SESSIONID=xxx&instance=xxx&client_version=xxx';
const socket = new WebSocket(socketUrl);
socket.onopen = function(event) {
console.log("Connection opened:", event);
};
socket.onmessage = function(event) {
console.log("Message received:", event.data);
};
socket.onerror = function(error) {
console.error("WebSocket error:", error);
};
socket.onclose = function() {
console.log("Connection closed");
};
Here’s the code I used in Node.js:
const socketUrl = 'wss://xxx.xxx.com/public/time/player/test/xxx/socket?messageFormat=json&SESSIONID=xxx&instance=xxx&client_version=xxx';
const WebSocket = require("ws");
const connect = () => {
const socket = new WebSocket(socketUrl);
// Stuck in CONNECTING
socket.on("open", () => {
console.log("Connected to socket");
});
socket.on("message", (data) => {
console.log("Received message:", data);
});
socket.on("close", () => {
console.log("Disconnected from socket");
connect();
});
socket.on("error", (err) => {
console.error("Socket error:", err);
socket.close();
});
};
connect();
Here is an image the headers from a successful connection in plain JavaScript:
successful connection