balderdashy / sails

Realtime MVC Framework for Node.js
https://sailsjs.com
MIT License
22.82k stars 1.95k forks source link

Sails.io - ECONNREFUSED in client #7319

Open Faresalghazy opened 7 months ago

Faresalghazy commented 7 months ago

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 commented 7 months ago

@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:

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 commented 7 months ago

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

ImoucheG commented 5 months ago

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' };

eric-centrifuge commented 4 months ago

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 commented 4 months ago

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

@Faresalghazy does this resolve this issue for you too?