node基础学习——网络操作

编写高性能web服务器

http部分

req和res的梳理
均可直接访问头数据如req.method res.headers等;均可req.on(‘data’/‘end’,function(){})
一个实际的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//客户端 发送请求
http.get('http://127.0.0.1:8080',function(res){
//http.request({hostname:'',port:8080},function) post请求时可如此。Q:此例如此写无法执行,因为本地主机的原因?
var body = [];
res.on('data',(chunk)=>{
body.push(chunk);
}); //服务器返回的数据
res.on('end',()=>{
console.log(body.toString());//body本身输出是二进制buffer数组
})
})
//服务器端
http.createServer((req,res)=>{
res.writeHead(200,{'Content-Type':'text/plain'});
res.write('hello');
res.end();
}).listen(8080)

HTTPS

和http类似,只是多了额外的SSL证书配置。
//服务器端
var options = {
key:fs.readFileSync(‘./ssl/default.key’), //服务器使用的私钥
cert:fs.readFileSync(‘./ssl/default.cer’) //服务器使用的公钥
} //相比于http多了该参数
var server = https.creatServer(options,(req,res)=>{

})
//SNI技术,即此服务器为多个域名提供服务
//添加不同域名证书
server.addContext(‘foo.com’,{
key:…,
cert:…
})
//客户端模式发起请求
https.request(options,(res)=>{ //别和服务器的options混了,这里是请求头、主机端口等信息

})

url

""
url字符串:比如http://user:pass@host.com:8080/p/a/t/h?query=string#hash
url对象:每一部分拆解开
转换方式:url.parse(‘url字符串’) 转换成对象
parse的另外两个参数:参数二为true,query字段返回的不是字符串而是queryString处理后的参数对象;参数三为true,可正确解析不含协议头的url如’//www.baidu.com'
url.format(‘url对象’) 转换成url字符串
url.resolve(‘www.baidu.com','/hank') 拼接url(引申:path.join是拼接文件路径哦)

queryString

url参数字符串和对象互相转换。解析url查询参数。
querystring.parse(‘foo=bar&b=w’) 得{foo:bar,b:w}
querystring.stringify({})

zlib模块

开启gzip压缩功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//服务器端。压缩HTTP响应体数据发给客户端。判断客户端是否开启,再决定是否启用
http.createServer((req,res)=>{
//测试数据
var i = 1024,data='';
while(i--) {
data += '.';
}
if((req.headers['accept-encoding']).indexOf('gzip')!==-1){ //此处可以用正则表达式来写!
zlib.gzip(data,(err,data){
res.writeHead(200,{
'Content-Type':'text/plain',
'Content-Encoding':'gzip' //accept-encoding和content-encoding
});
res.end(data);
});
} else {
//不设置gzip即可
}
}).listen(8080)
//客户端。收到响应体数据进行解压缩。判断服务器端是否使用gzip,是的话进行解压
var options = {
...
headers:{
'Accept-Encoding':'gzip,deflate' //两种压缩方式,服务器会根据这决定返回哪种压缩文件
}
}
http.request(options,(res)=>{
var body = [];
res.on('data',(chunk)=>{
body.push(chunk)
});
res.on('end',()=>{
body = Buffer.concat(body);
if(res.headers['Content-Encoding']==='gzip'){ //或者switch(res.headers['content-encoding'])判断是gzip or deflate等
zlib.gunzip(body,(err,data){
console.log(data.toString())
})
} else {
console.log(body)
}
})
})

net模块

创建socket服务器或客户端。
socket协议是传输控制层的,websocket是应用层