node.js的“net”包中的socket.write函数没有写入套接字

我在使用node.js的net包编写2个消息到TCP套接字时遇到了一些麻烦。

代码:

var net = require('net'); var HOST = '20.100.2.62'; var PORT = '5555'; var socket = new net.Socket(); socket.connect (PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client socket.write('@!>'); socket.write('RIG,test,test,3.1'); }); // Add a 'data' event handler for the client socket // data is what the server sent to this socket socket.on('data', function(data) { console.log('DATA: ' + data); // Close the client socket completely // client.destroy(); }); socket.on('error', function(exception){ console.log('Exception:'); console.log(exception); }); socket.on('drain', function() { console.log("drain!"); }); socket.on('timeout', function() { console.log("timeout!"); }); // Add a 'close' event handler for the client socket socket.on('close', function() { console.log('Connection closed'); }); 

我也尝试了net包中没有运气的所谓更正确的net.createConnection(arguments …)函数。

我可以看到在我的服务器端,连接到套接字发生正如所料,但没有收到服务器的数据,这就是为什么我怀疑,我使用socket.write函数的方式有什么问题。 也许第一个string字符造成混乱?

任何帮助将不胜感激。

非常感谢。

这取决于你在说什么服务器,显然,但你应该用换行符来划分你的数据\n

 socket.write('@!>\n'); socket.write('RIG,test,test,3.1\n'); 

对于某些服务器,您可能需要\r\n