本文实例讲述了Node.js服务器监听方法。分享给大家供大家参考,具体如下:
httpsnifferInvoke.js
var http = require('http');var sniffer = require('./httpsniffer');var server = http.createServer(function(req, res){ res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n');});sniffer.sniffOn(server);server.listen(3000);
httpsniffer.js
//http sniffer 监听每个服务器事件,然后输出每个事件的相关信息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', function(req, res){ util.log('e_checkContinue'); util.log(reqToString(req)); res.writeContinue(); }); server.on('upgrade', function(req, 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程序设计有所帮助。