我正在使用TLS模块在node.js中创建一个简单的服务器。到目前为止,客户端能够连接,发送数据和断开与服务器的连接。但是,我想在断开与服务器的连接时打印客户端的IP地址。就目前而言,我能够从事件回调函数外部打印客户端的IP地址,但我不能在回调中执行此操作(检查on('end)
)。
var tls = require('tls');
var fs = require('fs');
var server = tls.createServer({
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
}, function(cleartextStream) {
cleartextStream.setEncoding('utf8');
/*
* Error receiving data.
*/
cleartextStream.on('error', function (exception) {
});
/*
* Signal that it is safe to write again.
*/
cleartextStream.on('drain', function () {
});
/*
* New data received.
*/
cleartextStream.on('data', function (data) {
console.log('New data: '+data);
});
/*
* Remote client disconnected.
*/
console.log(cleartextStream.remoteAddress); // This prints the IP address correctly.
cleartextStream.on('end', function () {
console.log(cleartextStream.remoteAddress); // This prints undefined.
});
/*
* Server is shutting down.
*/
cleartextStream.on('close', function () {
});
});
server.listen(8000, function() {
console.log('Server listening.');
});
答案 0 :(得分:0)
在remoteAddress
事件触发之前,cleartextStream
的{{1}}属性似乎已被移除。因此,捕获远程地址,使其在'end'
事件回调中仍然可用:
'end'