3

I have done my first app with SailsJs. At the moment I'm using ajax to retrieve data for page, but I'd like to change it to use sockets. I have a cron job running on server and my purpose is to send message to all connected clients after every cron job done. I can see echo example from github: https://github.com/balderdashy/sails-docs/blob/0.9/sockets.md, but it's not quite what I need. I rather see server sending messages, no need for clients send anything but listen.

Server side CronController.js

// including my cron script
var cron = require('../../assets/js/cron');

module.exports = {
   index: function (req, res) {
        // including cron job module
        var cronJob = require('cron').CronJob;
        var job = new cronJob('0,10,20,30,40,50 * * * * *', 
            function() {
                cron.run();
            }, function () {
                console.log('cron done');
            },
            true,
            null
        );
        return res.json({
            message: 'running cron...'
        });
    },
    _config: {}
};

Server side cron.js

var io = require('socket.io').listen(8887);
io.sockets.on("connection", function (s) {
    s.emit('welcomemessage', { hello: "world" });
});

// Later on code
io.sockets.emit('Cron done', {msg:"msg"});

Client side script.js

socket.on('welcomemessage', function (json) {
    console.log(json);
});

socket.on('Cron done', function (json) {
    console.log(json);
});

I also changed socket.io.js port: 8887

console says: info - socket.io started and webpage localhost:8887 gives indication socket is working, but I get no welcome message or other messages to client side...

Other threads dealing with same question:

node.js + socket.io broadcast from server, rather than from a specific client?

emit socket.io and sailsjs (Twitter API)

Node.js client for a socket.io server

SOLUTION

I found socket variable on client side is able to get messages thru controller actions:

socket.get("/mycontroller", function (response) { console.log(response); });

So what I had to do was:

var s = io.connect("http://localhost:8887");

s.on('welcomemessage', function (json) {
    console.log(json);
});
Community
  • 1
  • 1
MarkokraM
  • 980
  • 1
  • 12
  • 26

0 Answers0