nodejs (四) 构建HTTP服务器和客户端
来源:互联网 发布:软件企业退税政策 编辑:程序博客网 时间:2024/05/22 06:31
1. 构建HTTP服务器
1.1 简单程序
var http= require('http');var server = http.createServer();server.on('request',function(req, res){ res.writeHead(200,{'Content-Type':'text/plain'}); res.write("hello world"); res.end();});server.listen(4000);
可以简写为:
var http =require('http');http.createServer(function(req,res){ }).listen(4000);
说明:(1)当有新客户端连接时,就执行回调函数。回调函数包含两个对象。
(2) request对象:了解请求的细节。
req.url 包含客户请求的URL(不包含模式主机名和端口号)
req.method 包含在请求上用到的HTTP方法例如:GET,POST,HEAD…
req.headers 包含一个对象,这个对象拥有请求上所有的HTTP头。(request对象是可读流,所以可以监听data事件。)
(3)util.inspect() 分析任意对象属性的使用函数。用它来分析req.headers
(4)reponse对象:它可以写入响应头和响应主体。
1.2 以流的形式传送HTTP分块响应。
HTTP分块编码允许服务器持续向客户端发送数据,而不需要发送数据的大小。根据HTTP规范默认的响应头可以让客户端数据接收若干块数据作为响应主体,并在客户端结束响应之前,发送一个具有0长度的结束块。这对于向HTTP客户端流式传送文本、音频、视屏数据都非常有用。
(1) 向HTTP响应传送一部电影。
var http= require('http');var fs =require('fs');http.createServer(function(req,res){ res.writeHead(200, {'Content-Type' :'video/mp4'}); var rs = fs.createReadStream('test.mp4'); rs.pipe(res);}).listen(4000);
说明:打开浏览器转向http://127.0.0.1:4000 电影就会立即开始播放,即使它没有完全被加载。
1.2 简单的HTTP静态文件服务器。
文件路径是通过访问的url提供的:http://localhost:4000/file.text
var fs =require('fs');var path= require('path'); require('http').createServer(function(req,res){ var file = path.normalize('.' + req.url); function reportError(err){ console.log(err.message); res.writeHead(500); res.end("Internal ServerError"); } path.exists(file, function(exists){ //看文件路径是否存在 if(exists){ fs.stat(file, function(err,stat){ //查看文件信息 if(err){ return reportError(err); } if(stat.isDirectory()){ res.writeHead(403); res.end('Forbidden'); }else{ rs =fs.createReadStream(file); rs.on('error',reportError); res.writeHead(200); rs.pipe(res); } }); }else{ res.writeHead(404); res.end('Not found'); } });}).listen(4000);<span style="font-size:18px; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>
2. 创建HTTP请求。
2.1 创建Get请求
var http= require('http');varoptions = { host : "www.baidu.com", port : 80, path : "/index.html"};http.get(options,function(res){ console.log('Gotresponse:'+res.statusCode); //Gotresponse:200});
2.2 创建其他请求
(1)http.get是通用的http.request的快捷方式,其选项(options)如下:
host: 想发送请求的主机名或者IP地址
port: 远程服务器的TCP端口号
method: 请求方法的字符串,Get是默认,PUT,DELETE,POST
path: 请求路径。可以/index?path=2
headers: 表示值-名称对的形式的请求头对象。Eg:
{
"Accept" : "text/json",
"If-Modiffied-Since": "Sat,28 ..."
}
(2) http.request 函数会返回一个http.ClientRequest对象,它是一个可写流,可以使用这个流发送数据。将请求主体部分写入该对象。
request.write(str, encoding); 第二个是可选参数。
(3) 发送请求成功之后,如果有来自服务器的响应(response),就会执行一个回调函数。function (res){} 而通过查看res对象,就可以发现服务器分配给请求的响应状态码以及服务器发送的响应头。例如查看该对象的属性:
res.statusCode: 一个整数,表示HTTP响应状态码
res.httpVersion: HTTP版本号
res.headers: 响应头
(4) 获取响应主体
res.on('data',function(data){ //获取响应主体
console.log('body:', data);
});
程序:
var http =require('http');var options = { host : "www.google.com", port: 80, path : "/upload", method : "post"};var request =http.request(options, function(res){ //函数返回request console.log('status:',res.statusCode); //响应状态码 console.log('headers:', res.headers); //响应头 res.setEncoding('utf8'); res.on('data', function(data){ //获取响应主体 console.log('body:', data); });}); request.write('this is a piece of data.\n'); //使用request.write()后一定要使用request.end()否则服务器以为数据还没有发送完。 request.end();
2.3 使用第三方请求模块,简化HTTP请求
(1) 本地模式安装: npm install request
(2) 使用:var request = require(‘request’);
(3) resquest(url, function(err,res, body){}); 接收响应和响应主体缓冲区,将他们传递给回调函数。
或者: request.post(options,function(err, res, body){});
- nodejs (四) 构建HTTP服务器和客户端
- nodejs-构建http服务器
- nodejs(三)构建TCP服务器和客户端
- nodejs 原生代码实现http 服务器和客户端并交互
- [NodeJS]创建HTTP、HTTPS服务器与客户端
- VLC构建服务器和客户端
- nodeJS之http搭建服务端和客户端
- [NodeJS]创建HTTP、HTTPS服务器与客户端区别
- nodejs 创建http客户端
- nodejs-http客户端
- nodejs中tcp服务器和http服务器实现的异同
- http服务器(nodejs)
- 创建 nodejs HTTP服务器
- NodeJS 创建TCP服务器 客户端
- 构建简单http服务器
- C# HTTP服务器构建
- NodeJS与多核HTTP服务器
- NodeJS与多核HTTP服务器
- onWindowFocusChanged重要作用 and Activity生命周期
- Linux使用_设置Tab键
- js将标准时间格式转化为时间戳
- 通讯录调用及委托实现
- Redis使用手册
- nodejs (四) 构建HTTP服务器和客户端
- java文本文件操作
- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? 问题
- iframe标红,不影响原来字体
- ios开发之UITextField特性
- iOS FLEX等内调试工具注意事项
- "Device /dev/ttyS? is locked."
- BlockingQueue介绍
- uImage