0

I have my Node.js script using socket.io. I understand how it works when the server answer to a client message. What I want to do it's that the server sends messages on his own when the execution of a function is over. I don't know how to proceed, can you help me ?

Here is my code :

function myfunction(){
   // instructions
   setTimeout(function(){
      otherfunction(function(ans){
         /*
           I want to send a message via socket.io over here
         */
      });
      myfunction();
   }, 30000);

}

var server=https.createServer(options, function (req, res) {
    // instructions
}.listen(443);

var io=require('socket.io').listen(server, {log:false});
io.sockets.on('connection', function(socket){
     socket.on('request', function(msg){
           // instructions
     });
});

It will be very good if you can help me doing this. Thank you for your help.

user3224275
  • 49
  • 1
  • 8

2 Answers2

0

Since nodeJS is eventbased, you cannot do this in a normal fashion as you do with normal JS. The way to go is using a callback function, which is executed at the end of your function.

Basically you pass a function as an argument and then runs that function at the of myFunction.

See this fiddle - http://jsfiddle.net/Fizk/NR2c8/

// Declaring myfunction
function myFunction(arg1, callback){
 console.log(arg1)
 callback();
}


// Calling myFunction with a callback
myFunction("This is a message",function(){
 console.log("This is a callback");
})
Fizk
  • 1,015
  • 1
  • 7
  • 19
  • Thank you for helping, yes I did that but what I don't know to do is : how can I send a message with socket.io to the good http client out of my "io.socket" block ? – user3224275 Feb 06 '14 at 14:56
  • Oh, sorry I misunderstood your question then :) To send a message, you should use either `socket.broadcast.emit("request","this is my request") ` or `socket.emit("request","this is my request")` Check out this question to see what the difference is http://stackoverflow.com/questions/10342681/whats-the-difference-between-io-sockets-emit-and-broadcast – Fizk Feb 06 '14 at 15:05
  • Yes I know the difference, but I want to put my socket.emit out of the "io.sockets.on('connection', function(socket){})" block. I tried to put my socket in a global variable, but the emit is sent to my two browsers. – user3224275 Feb 06 '14 at 15:50
0

You can do it like this if you want to emit the data to all connected clients:

function myfunction(){
setTimeout(function(){
  otherfunction(function(ans){
     io.sockets.emit('event name', {data: yourData});
  });
  myfunction();
}, 30000);
}

If you want to emit to individual clients then use this:

io.sockets.socket(socketid).emit('event name', {data: yourData});
M Omayr
  • 1,351
  • 1
  • 9
  • 19