【nodejs学习】2.网络相关

时间:2024-10-12 18:36:55

1.官方文档的一个小例子

//http是内置模块

var http = require('http');

http.createServer(function(request, response){

response.writeHead(200, {'Content-Type':'text-plain'});

response.end('hello World\n');

}).listen(8124);

.createServer创建服务器,.listen方法监听端口

HTTP请求是一个数据流,由请求头,请求体组成。

POST / HTTP/1.1
User-Agent: curl/7.26.0
Host: localhost
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded Hello World

2.请求发送解析数据

HTTP请求在发送给服务器时,可以按照从头到尾的一个顺序一个字节一个自己地以数据流方式发送,http模块创建的HTTP服务器在接收到完整的请求头后,就回调用回调函数,在回调函数中,除了可以用request对象访问请求头数据外,还能把request对象当做一个只读数据流访问具体请求体的数据。

var http = require('http');
http.createServer(function(request, response){

var body = [];

console.log(request.method);

console.log(request.headers);

request.on('data', function(chunk){

body.push(chunk+'\n');   
    });   
    response.on('end', function(){       
        body = Buffer.concat(body);       
        console.log(body.toString());   
    });

}).listen(3001);

//response写入请求头数据和实体数据

var http = require('http');

http.createServer(function(request, response){

response.writeHead(200, {'Content-Type':'text/plain'});

request.on('data', function(chunk){

response.write(chunk);

});

request.on('end', function(){

response.end();

});

}).listen(3001);

3.客户端模式:

var http = require('http');

var options = {

hostname: 'www.renyuzhuo.win',

port:80,

path:'/',

method:'POST',

headers:{

'Content-Type':'application/x-www-form-urlencoded'

}

};

var request = http.request(options, function(response){

    console.log(response.headers);

});

request.write('hello');

request.end();

//GET便捷写法

http.get('http://www.renyuzhuo.win', function(response){});

//response当做一个只读数据流来访问

var http = require('http');

var options = {

hostname: 'www.renyuzhuo.win',

port:80,

path:'/',

method:'GET',

headers:{

'Content-Type':'application/x-www-form-urlencoded'

}

};

var body=[];

var request = http.request(options, function(response){

console.log(response.statusCode);

console.log(response.headers);

response.on('data', function(chunk){

body.push(chunk);

});

response.on('end', function(){

body = Buffer.concat(body);

console.log(body.toString());

});

});

request.write('hello');

request.end();

https:https需要额外的SSL证书

var options = {

    key:fs.readFileSync('./ssl/dafault.key'),

cert:fs.readFileSync('./ssl/default.cer')

}

var server = https.createServer(options, function(request, response){});

//SNI技术,根据HTTPS客户端请求使用的域名动态使用不同的证书

server.addContext('foo.com', {

    key:fs.readFileSync('./ssl/foo.com.key'),

cert:fs.readFileSync('./ssl/foo.com.cer')

});

server.addContext('bar.com',{

    key:fs.readFileSync('./ssl/bar.com.key'),

cert:fs.readFileSync('./ssl/bar.com.cer')

});

//https客户端请求几乎一样

var options = {

    hostname:'www.example.com',

port:443,

path:'/',

method:'GET'

};

var request = https.request(options, function(response){});

request.end();

4.URL

http: // user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash

-----      ---------          --------         ----   --------     -------------       -----

protocol     auth      hostname    port pathname     search     hash

.parse方法将URL字符串转换成对象

url.parse("http: // user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash);

/*

Url

{

protocol: 'http:',

slashes: null,

auth: null,

host: null,

port: null,

hostname: null,

hash: '#hash',

search: '?query=string%20',

query: 'query=string%20',

pathname: '%20//%20user:pass%20@%20host.com%20:%208080%20/p/a/t/h%20',

path: '/p/a/t/h?query=string',

href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'

}

*/

.parse还支持第二个第三个参数,第二个参数等于true,返回的URL对象中query不再是一个字符串,而是一个经过querystring模板转换后的参数对象,第三个参数等于true,可以解析不带协议头的URL例如://www.example.com/foo/bar

.resolve方法可以用于拼接URL。

5.Query String

URL参数字符串与参数对象的互相转换。

querystring.parse('foo=bar&baz=qux&baz=quux&corge');

/*=>

{foo:'bar',baz:['qux','quux'],coge:''}

*/

querystring.stringify({foo:'bar',baz:['qux', 'quux'],corge:''});

/*=>

'foo=bar&baz=qux&baz=quux&corge'

*/

6.Zlib

数据压缩和解压的功能。如果客户端支持gzip的情况下,可以使用zlib模块返回。

http.createServer(function(request, response){

    var i = 1024, data = '';

while(i--){

data += '.';

}

if((request.headers['accept-eccoding']||'').indexOf('gzip')!=-1){

zlib.gzip(data, function(err, data){

response.writeHead(200, {

'Content-Type':'text/plain',

'Content-Encoding':'gzip'

});

response.end(data);

});

}else{

response.writeHead(200, {

'Content-Type':'text/plain'

});

response.end(data);

}

}).listen(3001);

判断服务端是否支持gzip压缩,如果支持的情况下使用zlib模块解压相应体数据。

var options = {

    hostname:'www.example.com',

port:80,

path:'/',

method:'GET',

headers:{

'Accept-Encoding':'gzip,deflate'

}

};

http.request(options, function(response){

    var body = [];

response.on('data', function(chunk){

body.push(chunk);

});

response.on('end', function(){

body = Buffer.concat(body);

if(response.headers[] === 'gzip'){

zlib.gunzip(body, function(err, data){

console.log(data.toString());

});

}else{

console.log(data.toString());

}

});

});

7.Net

net可创建Socket服务器与Socket客户端。从Socket层面来实现HTTP请求和相应:

//服务器端

net.createServer(function(conn){

    conn.on('data', function(data){

conn.write([

'HTTP/1.1 200 OK',

'Content-Type:text/plain',

'Content-length: 11'

'',

'Hello World'

].join('\n'));

});

}).listen(3000);

//客户端

var options = {

port:80,

host:'www.example.com'

};

var clien = net.connect(options, function(){

    clien.write([

'GET / HTTP/1.1',

'User-Agent: curl/7.26.0',

'Host: www.baidu.com',

'Accept: */*',

'',

''

].join('\n'));

});

clien.on('data', function(data){

console.log(data.toString());

client.end();

});