0

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

1
  • Are you sure that the ask:refresh handler gets the socket itself as a parameter? Commented Oct 16, 2013 at 23:38

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.