6
我在使用node.js的net包编写2个消息到TCP套接字时遇到了一些麻烦。node.js的'net'包中的socket.write函数不写入套接字
代码:
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(参数...)从网包功能,没有运气。
我可以在我的服务器端看到与套接字的连接发生正如预期的那样,但服务器没有收到数据,这就是为什么我怀疑使用套接字的方式有什么问题.write函数。也许第一个字符串字符造成混乱?
任何帮助将不胜感激。
非常感谢。
我试过你的代码,使用'nc -l 5555'作为我的服务器,它似乎在节点0.6.10下正常工作。 – 2012-02-17 13:39:42
非常感谢您的努力!问题是,我可以使用nc或使用我自己编写的node.js服务器来使其工作(使用Node 0.5.11-pre但是),或者使用我自己编写的node.js服务器...它只是这个特定服务器(用java编写的),我不能连接到。我可以使用telnet连接并发送消息/数据,但使用Socket.write()时不会。正如我所说,当我在服务器日志文件上做一个尾巴时,我可以清楚地看到我已连接,但无论我尝试写入tcp套接字(使用上面的代码),它都不会显示出来。感谢您的回复,我很感激。 – RSwan 2012-02-17 14:12:12
在这种情况下,我猜你没有正确格式化数据。例如,你可能想尝试发送换行符(telnet会这样做)。尝试'socket.write('@!> \ n');'。 – 2012-02-17 14:14:08