user2888434
user2888434

Reputation: 1

calling a socket inside another socket using node.js and socket.io

I am a trying to use socket.io and node.js like this : The browser sends an event to socket.io, in the data event I call another server to get some data, and I would like to send back a message to the browser using a socket.emit. This looks like that :

socket.on('ask:refresh', function (socket) {
   const net = require("net");
   var response = new net.Socket();
   response.setTimeout(1000);
   response.get_response = function (command, port, host) {
     this.connect(port, host, function () {
       console.log("Client: Connected to server");
     });
     this.write(JSON.stringify({ "command": command }))
     console.log("Data  to server: %s", command);
   };
   response.on("data", function (data) {
     var ret = data.toString();
     var tmp_data = JSON.parse(ret.substring(0, ret.length - 1).toString());
     var data = new Object();
     var date = new Date(tmp_data.STATUS[0].When * 1000 );
     data.date = date.toString();
     socket.emit('send:refresh', JSON.stringify(data) );
   });
   response.get_response("version", port, host);
  });
};

The thing is that I cannot access "socket.emit" inside response.on. Could you please explain me how I can put a hand on this ?

Thanks a lot

Upvotes: 0

Views: 1324

Answers (1)

hexacyanide
hexacyanide

Reputation: 91799

You appear to be overwriting the actual socket with the one of the callback parameters:

socket.on('ask:refresh', function(socket) {
  // socket is different
});

Change the name of your callback variable, and you won't have this problem.

Upvotes: 4

Related Questions