我的代码片段有一点问题。我写了一个例子来学习一个项目的 TCP Socket 通信。目前我可以发送一个 TCP 套接字并阅读答案,但我想在其他软件部分使用答案。为此,我尝试使用变量 socketmessage 但这不起作用。有人知道我的问题的答案吗?非常感谢
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;
}
终端:套接字消息:未定义客户端:{“请求”:“状态”}服务器:{“状态”:0.000000}