本文實例講述了Node.js服務器監(jiān)聽方法。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)專注于企業(yè)網(wǎng)絡營銷推廣、網(wǎng)站重做改版、渭源網(wǎng)站定制設計、自適應品牌網(wǎng)站建設、H5場景定制、商城網(wǎng)站建設、集團公司官網(wǎng)建設、外貿網(wǎng)站建設、高端網(wǎng)站制作、響應式網(wǎng)頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為渭源等各大城市提供網(wǎng)站開發(fā)制作服務。
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 監(jiān)聽每個服務器事件,然后輸出每個事件的相關信息 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程序設計有所幫助。