本文实例讲述了Node.js服务器监听方法。分享给大家供大家参考,具体如下:
httpsnifferInvoke.js
httpsniffer.js
输出每个事件的相关信息
var url = require('url');
var util = require('util');
exports.sniffOn = function(server){
server.on('request',function(req,res){
util.log('e_request');
util.log(reqToString(req));
});
server.on('close',function(error){
util.log('e_close error=' + error);
});
server.on('checkContinue',res){
util.log('e_checkContinue');
util.log(reqToString(req));
res.writeContinue();
});
server.on('upgrade',socket,head){
util.log('e_upgrade');
util.log(reqToString(req));
});
server.on('clientError',function(){
util.log('e_clientError');
});
}
var reqToString = function(req){
var ret = 'request' + req.method + ' ' + req.httpVersion + ' ' + req.url + '\n';
ret += JSON.stringify(url.parse(req.url,true)) + '\n';
var keys = Object.keys(req.headers);
for (var i = 0; i < keys.length; i++){
var key = keys[i];
ret += i + ' ' + key + ': ' + req.headers[key] + '\n';
}
if (req.trailers) ret += req.trailers + '\n';
return ret;
}
exports.reqToString = reqToString;
希望本文所述对大家nodejs程序设计有所帮助。
原文链接:https://www.f2er.com/nodejs/39983.html