2
var net = require('net');
var HOST = '0.0.0.0';
var PORT = 5000;
// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
if (data === "exit") {
console.log('exit message received !')
}
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
无论我怎么努力,我不能让:节点JS读取TCP套接字特定消息net.createServer
if (data === "exit") {
console.log('exit message received !')
}
的工作,它总是假的。
我通过telnet连接并发送“退出”,服务器应该进入“if”循环并说“退出消息收到”。这从来没有发生,有人可以摆脱一些光?谢谢
编码提示是正确的。但它仍然不能可靠地工作,因为套接字可能不会一次发送完整的请求字节。 “退出”可能分布在几个接收到的缓冲区中,或可能包含在也包含其他数据的缓冲区中。 – Matthias247
你说的对,很多变量可能发生在应该被处理的输入数据中,但为了解决他的问题,telnet不会把他的字符串“退出”,它太小了。 – shuji