我有一个简单的 TCP 服务器,如下所示:
var net = require('net');
var PORT = 6346;
var server = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Client connected: ' + socket.remoteAddress);
socket.write('Welcome to the server!\r\n');
});
socket.on('end', function() {
console.log('Client disconnected: ' + socket.remoteAddress);
});
socket.on('error', function() {
console.log('Client error: ' + socket.remoteAddress);
});
socket.on('timeout', function() {
console.log('Client timed out:' + socket.remoteAddress);
});
}).listen(PORT);
当我连接到服务器时,我看到预期的 Client connected: 127.0.0.1
但当我断开连接时,我看到 Client disconnected: undefined
。为什么未定义 socket.remoteAddress 以及如何在断开连接时记录客户端的 IP?
最佳答案
问题是socket断开后,某些属性(如remoteAddress
)不再可用!
您可以通过用您自己的对象包装套接字,或者在连接时在其他地方跟踪该远程地址来解决这个问题。 (求关闭。)
关于sockets - 为什么在 'end' 事件上未定义 socket.remoteAddress?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444598/