1

I'm trying to keep a tcp socket open after it successfully connects so I can write something through it later. Here is my attempt at doing that:

var sock = null;

var server = require('net').createServer( function (socket) {
  sock = socket;

  socket.on('data', function (data) {
    console.log(data.toString());
  });

});

server.listen(10005);


if (sock != null) {
  sock.write('command', 'utf-8');
else {
  console.log('sock is null');
}

I didn't realize it's asynchronous so the null check on sock happens first before the connectionCallback. I came from a C++ background so this is how I was trained to think program-atically. What is the proper way to do this in javascript?

I want the user to be able to write data through the connection socket. I want to reuse that same socket that was successfully connected for writing.

Thanks.

user3904534
  • 309
  • 5
  • 13

1 Answers1

1

Instead of storing socket in a variable I would write a function to handle writing that would be called when the socket is created. Something like this:

function handleSocket(socket) {
  socket.write('command', 'utf-8')
}

var server = require('net').createServer(function (socket) {
  socket.on('data', function (data) {
    console.log(data.toString());
  });

  handleSocket(socket);
});

server.listen(10005);

I am not sure what else you want to do with the socket, but the pattern would be the same - you get some data and conditionally call some callback.

m1ch4ls
  • 3,317
  • 18
  • 31