首页 文章

node.js'“net”包中的TCP socket.write函数没有写入socket

提问于
浏览
7

我在使用node.js的网络包将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.createConnection(arguments ...)函数,但没有运气 .

我可以在我的服务器端看到与套接字的连接正如预期的那样发生,但服务器没有收到数据,这就是为什么我怀疑我使用socket.write函数的方式有问题 . 也许第一个字符串字符引起混乱?

任何帮助将不胜感激 .

非常感谢 .

1 回答

  • 16

    显然,这取决于你正在与哪台服务器对话,但你应该用换行符分隔你的数据 \n

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

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

相关问题