I have a Node.js server using socket.io
that accepts connections from clients via HTTPS.
I know this server works as I am able to connect to it via browser.
The problem is that I can't create a node app to connect to this server as a client.
I am using the following code:
const io = require("socket.io-client");
const socket = io.connect("https://my.website.com:3002", { secure: true, reconnect: true });
socket.on("connect", function(){
console.log("connected");
});
socket.on("disconnect", function(){
console.log("disconnected");
});
socket.on("error", console.error);
The server registers no connections, and this app logs no errors. It would seem that I am connecting to the wrong server, but this same URL works just fine when I use a browser.
I have searched github and the official docs for an answer. Even similar questions from stackoverflow seem to not work:
What am I doing wrong ?
Problem: the socket is not able to connectYou are trying to reach a plain WebSocket server. The server is not reachable. The client is not compatible with the version of the server. The server does not send the necessary CORS headers.
After realising, that not all errors feed into the "error"
event ( special thanks to @RolandStarke ) I found that I was having a consistent XHR pool request:
{ Error: xhr poll error
at XHR.Transport.onError (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transport.js:64:13)
at Request.<anonymous> (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:128:10)
at Request.Emitter.emit (/Users/pedro/Workspace/backend-stresser/node_modules/component-emitter/index.js:133:20)
at Request.onError (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:310:8)
at Timeout._onTimeout (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:257:18)
at ontimeout (timers.js:469:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:264:5) type: 'TransportError', description: 503 }
Once I had this information, I made a quick search and found a solution to this issue, which seems to be a bug:
The code I am now using is:
const socket = io.connect("https://my.website.com:3002", { secure: true, reconnection: true, rejectUnauthorized: false });
And it works as expected.
I have used this code in my client side and it worked:
import io from "socket.io-client"
const SERVER = "http://localhost:5000"
const socket = io(SERVER, { transports: ["websocket"] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With