Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sails.io - ECONNREFUSED in client #7319

Open
Faresalghazy opened this issue Feb 2, 2024 · 5 comments
Open

Sails.io - ECONNREFUSED in client #7319

Faresalghazy opened this issue Feb 2, 2024 · 5 comments

Comments

@Faresalghazy
Copy link

Faresalghazy commented Feb 2, 2024

Node version: v20.9.0
Sails version (sails): 1.5.9
ORM hook version (sails-hook-orm): 4.0.2
Sockets hook version (sails-hook-sockets): 3.0.0
Organics hook version (sails-hook-organics):
Skipper adapter & version (e.g. skipper-s3@5.55.5): 0.9.4


Very similar to issue #7104
Node Client Code:

var io = require('sails.io.js')(require('socket.io-client'));
io.sails.url = 'http://localhost:1337';

io.socket.on('connect', function() {
    console.log('Connected to the server');
    io.socket.get('/subscribeToPrices', function(resData, jwres) {
        console.log('Subscription response:', resData);
    });
});

io.socket.on('message', function(data) {
    console.log('Received message:', data);
});

Error:

====================================
 The socket was unable to connect.
 The server may be offline, or the
 socket may have failed authorization
 based on its origin or other factors.
 You may want to check the values of
 `sails.config.sockets.onlyAllowOrigins`
 or (more rarely) `sails.config.sockets.beforeConnect`
 in your app.
 More info: https://sailsjs.com/config/sockets
 For help: https://sailsjs.com/support

 Technical details:
 TransportError: websocket error
    at WS.onError (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\engine.io-client\build\cjs\transport.js:47:37)
    at ws.onerror (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\engine.io-client\build\cjs\transports\websocket.js:77:39)
    at callListener (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\ws\lib\event-target.js:290:14)
    at WebSocket.onError (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\ws\lib\event-target.js:230:9)
    at WebSocket.emit (node:events:514:28)
    at emitErrorAndClose (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\ws\lib\websocket.js:1002:13)
    at ClientRequest.<anonymous> (C:\Users\fares.alghazy\Desktop\Development\scraps\sails-client\node_modules\ws\lib\websocket.js:854:5)
    at ClientRequest.emit (node:events:514:28)
    at Socket.socketErrorListener (node:_http_client:495:9)
    at Socket.emit (node:events:514:28) {
  description: ErrorEvent {
    [Symbol(kTarget)]: WebSocket {
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      _binaryType: 'nodebuffer',
      _closeCode: 1006,
      _closeFrameReceived: false,
      _closeFrameSent: false,
      _closeMessage: <Buffer >,
      _closeTimer: null,
      _extensions: {},
      _paused: false,
      _protocol: '',
      _readyState: 2,
      _receiver: null,
      _sender: null,
      _socket: null,
      _bufferedAmount: 0,
      _isServer: false,
      _redirects: 0,
      _url: 'ws://localhost:1337/engine.io/?EIO=4&transport=websocket',
      _req: null,
      [Symbol(kCapture)]: false
    },
    [Symbol(kType)]: 'error',
    [Symbol(kError)]: AggregateError
        at internalConnectMultiple (node:net:1114:18)
        at afterConnectMultiple (node:net:1667:5) {
      code: 'ECONNREFUSED',
      [errors]: [Array]
    },
    [Symbol(kMessage)]: ''
  },
  context: undefined,
  type: 'TransportError'
}
 ====================================

Server code:
All my console logs do not print, including the beforeConnect
config./sockets.js

  beforeConnect: function (handshake, proceed) {

    // `true` allows the socket to connect.
    // (`false` would reject the connection)
    console.log(`preconnect\n${JSON.stringify(handshake)}`);
    return proceed(undefined, true);

  },

PriceFeedSocketController.js

module.exports = {
    subscribeToPrices: async function (req, res) {
        console.log(`Attempted connection to price sub`)
        if (req.isSocket) {
            console.log(`Connection to price sub`)
            sails.sockets.join(req, 'prices', function (err) {
                if (err) {
                    return res.serverError(err);
                }
                return res.ok();
            });
        } else {
            return res.badRequest();
        }
    }

};

helpers/add-to-socket-and-redis:

module.exports = {
    friendlyName: "Add to socket and redis",
    description: "Adds feed into socket room named `prices` then into redis ",
    inputs: {
        feed: {
            friendlyName: "Data feed",
            description: "List of key value pairs to be inserted and broadcasted",
            type: "json",
            defaultsTo: []
        }
    },
    fn:
        async function (inputs, exits) {
            const feed = inputs.feed;
            sails.sockets.broadcast('prices', feed);
            await sails.helpers.redisInsert.with({
                feed
            })
            return exits.success();
        }
}

config/security.js

cors: {
   allRoutes: true,
   allowOrigins: '*',
   allowCredentials: false
 }
@sailsbot
Copy link

sailsbot commented Feb 2, 2024

@Faresalghazy Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. (Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)
  • tell us why this issue is important to you and your team. What are you trying to accomplish? (Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. (Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. (Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. (Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

@DominusKelvin
Copy link
Contributor

Hey @Faresalghazy can you tell me the versions of socket.io-client and sails.io.js?

@mikermcneil mikermcneil added the needs version info Some (or all) version information is missing from this issue. label Mar 1, 2024
@ImoucheG
Copy link

ImoucheG commented Apr 10, 2024

Hi,
Last version of 'socket.io-client@4.X.X use default path to /engine.io
And on last Sails version the default path is /socket.io

If you socket server is an Sails, you can set the sails.config.sockets.path to /engine.io
Or you can change default path of socket.io-client to /socket.io if you prefer.

And on your client you must have set :

socket.initialConnectionHeaders = { __sails_io_sdk_version: '1.2.1', __sails_io_sdk_platform: 'node', __sails_io_sdk_language: 'javascript' };

@sailsbot sailsbot removed the needs version info Some (or all) version information is missing from this issue. label Apr 10, 2024
@eric-centrifuge
Copy link

Hi, Last version of 'socket.io-client@4.X.X use default path to /engine.io And on last Sails version the default path is /socket.io

If you socket server is an Sails, you can set the sails.config.sockets.path to /engine.io Or you can change default path of socket.io-client to /socket.io if you prefer.

And on your client you must have set :

socket.initialConnectionHeaders = { __sails_io_sdk_version: '1.2.1', __sails_io_sdk_platform: 'node', __sails_io_sdk_language: 'javascript' };

This resolved the issue on my end! Thanks!

@DominusKelvin
Copy link
Contributor

DominusKelvin commented Apr 25, 2024

Thanks @ImoucheG for sharing that solution. @eric-centrifuge I'm glad you are unblocked too.

@Faresalghazy does this resolve this issue for you too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

6 participants