Node.js TCP套接字在轮询前等待几秒钟? (net.createServer)

Node.js中有一个非常简单的TCP套接字 它连接到以XML格式发回数据的设备。 有一个C#程序可以做到这一点,但是我必须在Node.js中构build它。

所以,当设备发送消息时,我在5秒钟之后得到响应! C#程序在1秒或2秒后获取。

它看起来像“TCP套接字”具有特定的轮询频率或某种“等待function”。 这甚至可能吗? 每次显示传入的消息。 它还显示“sock.on('close')”的退出消息

看来5秒钟后“服务器”自动closures。 见底线“console.log('[LISTENER]连接暂停');” 之后,传入的消息得到正确显示。

我的代码有什么问题?

// Set Node.js dependencies var fs = require('fs'); var net = require('net'); // Handle uncaughtExceptions process.on('uncaughtException', function (err) { console.log('Error: ', err); // Write to logfile var log = fs.createWriteStream('error.log', {'flags': 'a'}); log.write(err+'\n\r'); }); /* ------------------------------------------------- Socket TCP : TELLER ------------------------------------------------- */ var oHOST = '10.180.2.210'; var oPORT = 4100; var client = new net.Socket(); client.connect(oPORT, oHOST, function() { console.log('TCP TELLER tells to: ' + oHOST + ':' + oPORT); // send xml message here, this goes correct! client.write(oMessage); }); // Event handler: incoming data client.on('data', function(data) { // Close the client socket completely client.destroy(); }); // Event handler: close connection client.on('close', function() { console.log('[TELLER] Connection paused.'); }); /* ------------------------------------------------- Socket TCP : LISTENER ------------------------------------------------- */ var iHOST = '0.0.0.0'; var iPORT = 4102; // Create a server instance, and chain the listen function to it var server = net.createServer(function(sock) { // We have a connection - a socket object is assigned to the connection automatically console.log('TCP LISTENER hearing on: ' + sock.remoteAddress +':'+ sock.remotePort); // Event handler: incoming data sock.on('data', function(data) { console.log('Message: ', ' '+data); }); // Event handler: close connection sock.on('close', function(data) { console.log('[LISTENER] Connection paused.'); }); }).listen(iPORT, iHOST); 

client.write()并不总是立即传输数据,它将等待,直到缓冲区已满,然后发送数据包。 client.end()将closures套接字并刷新缓冲区。

你可以试试这个: http : //nodejs.org/api/net.html#net_socket_setnodelay_nodelay

虽然你的5秒延迟似乎有点奇怪。

所以在“TELLER”中,我必须写下“sock.write(data)”; 在“sock.on('data',function(data)”事件中。

它现在有效。 感谢Jeremy和rdrey帮助我朝着正确的方向前进。