6

Background

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.

Problem

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.

Research

I have searched github and the official docs for an answer. Even similar questions from stackoverflow seem to not work:

Question

What am I doing wrong ?

Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266

2 Answers2

20

Answer

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.

аlex
  • 5,426
  • 1
  • 29
  • 38
Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
3

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"] })
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83