mecheng
mecheng

Reputation: 29

Node.js read TCPSocket and write to a variable

I've got a litte problem with my code snipet. I wrote a example to learn the TCP Socket Communication for a project. For the moment i can send a TCP Socket and read the answer, but i want to use the answer in other software parts. For that i tried to use the variable socketmessage but this doesn't work. Does anyone have the answer for my problem? Thanks a lot

var net = require('net');
var client = new net.Socket();
var HOST='127.0.0.1';
var PORT='20000';

var MSG="{\"REQUEST\":\"STATUS\"}";    
var socketmessage;

socketmessage=getSocketMessage(MSG);
console.log ("Socket Message: " + socketmessage);

function getSocketMessage(tcpmsg){
  var outData;

  client.connect(PORT, HOST, function() {
    console.log("Client: " + tcpmsg);
    client.write(tcpmsg);
  });

  client.setTimeout(5000, function() {  client.destroy(); });

  client.on('data', function(data) {
    console.log('Server: ' + data);
    outData = data.toString('utf8');
    console.log ("Socketmessage: " + outData);
    client.destroy();
  });

  //Add a 'close' event handler for the client socket
  client.on('close', function() {
    console.log('Connection closed');
  });

  // Add a 'error' event handler for the client socket
  client.on('error', function(error) {
    console.log('Error Connection: ' + error);
  });

  return outData;
}

Terminal: Socket Message: undefined Client: {"REQUEST":"STATUS"} Server: {"STATUS":0.000000}

Upvotes: 0

Views: 6444

Answers (2)

chandoo
chandoo

Reputation: 1316

You can create a read stream and once the stream ends you may process the data.

var readStream = fs.createReadStream(path of the file, 'utf8'); //you can use path.join(loc, filename)
 var data = '';
 readStream.on('data', function(chunk:any) {              
                data += chunk;
              }).on('end', function() {
                let gotContent = data.toString(); //
                doWhatEver(gotContent)  //the method is async or promose
              then(function(result){
                console.log(result); //desired output
              })

  });

Upvotes: 0

user568109
user568109

Reputation: 47993

This is because function getSocketMessage is asynchronous. You are trying to return the received message. The function returns immediately, outData being undefined then. Its value is set when data arrives from server. The network I/O is evented, the event you use is data

client.on('data', function(data) {

The received message can only be handled properly inside the event-handler for data. You would have to call your other part from here itself.

Upvotes: 2

Related Questions