I am trying to continously broadcast/publish/emit/send messages to a socket room using Sails on my backend, and on another project continously recieve these messages.
Expected behaviour : every time addToSocketAndRedis() is called, i see a console log on my client and on my server (from the controller)
Observed behaviour: Errors + no message My client code is:
var io = require('sails.io.js')(require('socket.io-client'));
// Specify the URL of your Sails server here
io.sails.url = 'http://localhost:1337';
io.socket.get('/subscribeToPrices', function (res) {
console.log(res);
});
io.socket.on('message', function (data) {
console.log(data);
});
And the error i get on the client:
====================================
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
My "onlyAllowOrigins" is commented out as default by Sails, so that is not the issue.
My Sails code:
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();
}
}
};
add-to-socket-and-redis.js
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();
}
}
routes.js:
module.exports.routes = {
'/': { view: 'pages/homepage' },
'/subscribeToPrices': 'PriceFeedSocket.subscribeToPrices',
};
config/security.js
cors: {
allRoutes: true,
allowOrigins: '*',
allowCredentials: false
}