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