http server

request:当服务器收到客户端请求时触发。例如:function callback(request,response){}.

connection:当一个新的TCP流建立时触发。例如:function callback (socket)

close:服务器关闭时触发,回调不接收参数。

checkContinue:当收到包括期待的100-continue标头的请求时触发。即使不处理此事件,默认的事件处理程序也响应。例如:function callback(request,response){}

connect:接收到HTTP CONNECT请求时发出。callback接收request、response、head。例如:function callback(request,response,head)

upgrade:当客户端请求HTTP升级时发出。function callback (request,response,head)

clientError:当客户端连接套接字发出一个错误时发出。function callback(error,socket){}

要启动HTTP服务器,首先使用createServer([requestListener])方法创建对象然后通过listen(port,[hostname],[backlog],[callback]).

port:端口

hostname:主机名

backlog(积压):指定被允许进行排队的最大待处理连接数。默认511.

callback(回调):指定该服务器已经开始在指定的端口监听时,要执行的回调处理程序。

对于文件系统的连接可以用下面的两种方法:

listen(path,[callback]):文件路径

listen(handle,[callback]):接收一个已经打开的文件描述符句柄。

如果要停止监听可以使用close([callback])方法。


<!--创建一个HTTP服务器-->
// 载入http核心模块
const http = require("http");
// 创建一个server对象
const server = http.createServer((req,res)=>{
   // 通过res对象,输出一些内容
   res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
   res.write("<h1>http服务器</h1>");
   res.write("<p>使用Node.js创建一个http服务器</p>");
   res.end();
});
// 开启server的监听
server.listen(8000,()=>{
    console.log("http server is listening in port 8000...");
});

猜你喜欢

转载自blog.csdn.net/qq_43198747/article/details/86605909