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.