响应部分相对比较简单,最简单的情况只需要发送两个记录就行了,那就是FCGI_STDOUT和FCGI_END_REQUEST。
具体记录实体的内容就不冗述了,直接看代码吧:
复制代码 代码如下:
var res = (function(){
var MaxLength = Math.pow(2, 16);
function buffer0(len){
return new Buffer((new Array(len + 1)).join('\u0000'));
};
function writeStdout(data){
var rcdStdoutHd = new Buffer(8),
contendLength = data.length,
paddingLength = 8 - contendLength % 8;
rcdStdoutHd[0] = 1;
rcdStdoutHd[1] = TYPES.FCGI_STDOUT;
rcdStdoutHd[2] = 0;
rcdStdoutHd[3] = 1;
rcdStdoutHd[4] = contendLength >> 8;
rcdStdoutHd[5] = contendLength;
rcdStdoutHd[6] = paddingLength;
rcdStdoutHd[7] = 0;
return Buffer.concat([rcdStdoutHd, data, buffer0(paddingLength)]);
};
function writeHttpHead(){
return writeStdout(new Buffer("HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\nConnection: close\r\n\r\n"));
}
function writeHttpBody(bodyStr){
var bodyBuffer = [],
body = new Buffer(bodyStr);
for(var i = 0, l = body.length; i < l; i += MaxLength + 1){
bodyBuffer.push(writeStdout(body.slice(i, i + MaxLength)));
}
return Buffer.concat(bodyBuffer);
}
function writeEnd(){
var rcdEndHd = new Buffer(8);
rcdEndHd[0] = 1;
rcdEndHd[1] = TYPES.FCGI_END_REQUEST;
rcdEndHd[2] = 0;
rcdEndHd[3] = 1;
rcdEndHd[4] = 0;
rcdEndHd[5] = 8;
rcdEndHd[6] = 0;
rcdEndHd[7] = 0;
return Buffer.concat([rcdEndHd, buffer0(8)]);
}
return function(data){
return Buffer.concat([writeHttpHead(), writeHttpBody(data), writeEnd()]);
};
})();
在最简单的情况下,这样就可以发送一个完整的响应了。把我们最终的代码修改一下:
复制代码 代码如下:
var visitors = 0;
server.on('connection', function(sock){
visitors++;
sock.on('data', function(data){
...
var querys = querystring.parse(params.QUERY_STRING);
var ret = res('欢迎你,' + (querys.name || '亲爱的朋友') + '!你是本站第' + visitors + '位用户哦~');
sock.write(ret);
ret = null;
sock.end();
...
});
打开浏览器访问:?name=yekai,可看到类似“欢迎你,yekai!你是本站第7位用户哦~”。
至此,我们就成功的使用Node.js实现了一个最简单的FastCGI服务。如果需要作为真正的服务使用,接下来只需要对照协议规范完善我们的逻辑就行了。
对比测试
最后,我们需要考虑的问题是这个方案具体是否具有可行性?可能已经有同学看出了问题,我先把简单的压测结果放上来:
复制代码 代码如下:
//FastCGI方式:
500 clients, running 10 sec.
Speed=27678 pages/min, 63277 bytes/sec.
Requests: 3295 susceed, 1318 failed.
500 clients, running 20 sec.
Speed=22131 pages/min, 63359 bytes/sec.
Requests: 6523 susceed, 854 failed.
//proxy方式:
500 clients, running 10 sec.
Speed=28752 pages/min, 73191 bytes/sec.
Requests: 3724 susceed, 1068 failed.
500 clients, running 20 sec.
Speed=26508 pages/min, 66267 bytes/sec.
Requests: 6716 susceed, 2120 failed.
//直接访问Node.js服务方式:
500 clients, running 10 sec.
Speed=101154 pages/min, 264247 bytes/sec.
Requests: 15729 susceed, 1130 failed.