我在Linux下使用C语言编写了一个简单的服务器,它在localhost上侦听端口80.现在,当我从浏览器google chrome向程序发送请求时,它收到2个请求,而当我从firefox发送时只收到一个请求.
我在浏览器中输入的URL是:http://localhost/xyz.html
当我在CHROME中输入URL时输出
root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN
Inside HTTP server Handler
Inside HTTP request Handler
**Detected request: clientsocket_fd = 6 clientportnumber = 38027**
GET /xyz.html HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Inside HTTP request Handler
**Detected request: clientsocket_fd = 7 clientportnumber = 38029**
^C
root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL#
Run Code Online (Sandbox Code Playgroud)
第二个请求不发送任何数据,所以我的代码在读取调用时等待,所以我必须终止它'^ C'.
我在FIREFOX中输入URL时的输出
root@anirudh-Aspire-5920:/home/anirudh/workspace/DCMTOL# ./DCMTOL_RUN
Inside HTTP server Handler
Inside HTTP request Handler
**Detected …Run Code Online (Sandbox Code Playgroud) var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
Run Code Online (Sandbox Code Playgroud)
这会根据我的Chrome浏览器的请求写入控制台:
收到请求收到请求
两次?为什么?
我之前做了一些节点实验
以下代码将"aaa"输出到控制台,并且浏览器会按预期等待响应.
var http = require("http");
http.createServer(function (req, res) {
//res.writeHead(200);
console.log("aaa");
//res.end("hello");
//console.log("test111");
//res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
Run Code Online (Sandbox Code Playgroud)
但是,只要我取消注释第一个res.end,节点就会在一次请求中将"aaa"写入控制台两次!
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200);
console.log("aaa");
res.end("hello");
//console.log("test111");
//res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
aaa
Run Code Online (Sandbox Code Playgroud)
最后,当我取消评论一切时,
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200);
console.log("aaa");
res.end("hello");
console.log("test111");
res.end("bye");
}).listen(5555);
Run Code Online (Sandbox Code Playgroud)
输出:
aaa
test111
aaa
test111
Run Code Online (Sandbox Code Playgroud)
知道为什么每个请求都会执行两次console.log语句吗?