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请求是一个数据流,由请求头,请求体组成。

  1. POST / HTTP/1.1
  2. User-Agent: curl/7.26.0
  3. Host: localhost
  4. Accept: */*
  5. Content-Length: 11
  6. Content-Type: application/x-www-form-urlencoded
  7. 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();

});

【nodejs学习】2.网络相关的更多相关文章

  1. NodeJS学习之网络操作

    NodeJS -- 网络操作 使用NodeJS内置的http模块简单实现HTTP服务器 var http = require('http'); http.createServer(function(r ...

  2. 七天学会NodeJS (原生NodeJS 学习资料 来自淘宝技术团队)

    NodeJS基础 什么是NodeJS JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器. ...

  3. NodeJS学习指南

    七天学会NodeJS NodeJS基础 什么是NodeJS 有啥用处 如何安装 安装程序 编译安装 如何运行 权限问题 模块 require exports module 模块初始化 主模块 完整示例 ...

  4. NodeJS 学习笔记一

    他创造NodeJS的目的是为了实现高性能Web服务器,他首先看重的是事件机制和异步IO模型的优越性,而不是JS.但是他需要选择一种编程语言实现他的想法,这种编程语言不能自带IO功能,并且需要能良好支持 ...

  5. Nodejs学习笔记(十六)--- Pomelo介绍&入门

    目录 前言&介绍 安装Pomelo 创建项目并启动 创建项目 项目结构说明 启动 测试连接 聊天服务器 新建gate和chat服务器 配置master.json 配置servers.json ...

  6. nodejs学习以及SSJS漏洞

    0x01 简介 什么是nodejs,it's javascript webserver! JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对 ...

  7. Nodejs学习笔记(十六)—Pomelo介绍&入门

    前言&介绍 Pomelo:一个快速.可扩展.Node.js分布式游戏服务器框架 从三四年前接触Node.js开始就接触到了Pomelo,从Pomelo最初的版本到现在,总的来说网易出品还算不错 ...

  8. NodeJS学习笔记 进阶 (13)Nodejs进阶:5分钟入门非对称加密用法

    个人总结:读完这篇文章需要5分钟,这篇文章讲解了Node.js非对称加密算法的实现. 摘录自网络 地址: https://github.com/chyingp/nodejs-learning-guid ...

  9. NodeJS学习笔记 进阶 (12)Nodejs进阶:crypto模块之理论篇

    个人总结:读完这篇文章需要30分钟,这篇文章讲解了使用Node处理加密算法的基础. 摘选自网络 Nodejs进阶:crypto模块之理论篇 一. 文章概述 互联网时代,网络上的数据量每天都在以惊人的速 ...

  10. NodeJS学习笔记 进阶 (1)Nodejs进阶:服务端字符编解码&乱码处理(ok)

    个人总结:这篇文章主要讲解了Nodejs处理服务器乱码及编码的知识,读完这篇文章需要10分钟. 摘选自网络 写在前面 在web服务端开发中,字符的编解码几乎每天都要打交道.编解码一旦处理不当,就会出现 ...

随机推荐

  1. error: expected constructor, destructor, or type conversion before '.' token

    今天写代码是遇到这样一个问题error: expected constructor, destructor, or type conversion before '.' token:立马网上查,原来是 ...

  2. Y - Design T-Shirt(第二季水)

    Description Soon after he decided to design a T-shirt for our Algorithm Board on Free-City BBS, XKA ...

  3. html5 利用canvas实现简单的人物走动

    最近在学习html5,其中涉及到很关键的元素canvas-画布,在网上下载了一些游戏源代码,虽然能看懂,但是想单独地针对某个功能提取出来还是有难处的,于是乎自己又上网查找了一些例子,才将超级玛丽简单的 ...

  4. php 面试

    1.在PHP中,当前脚本的名称(不包括路径和查询字符串)记录在预定义变量(1)中:而链接到当前页面的URL记录在预定义变量(2)中. 答:echo $_SERVER['PHP_SELF']; echo ...

  5. 生产环境下Centos 6.5优化配置 (装载)

    本文 centos 6.5 优化 的项有18处: 1.centos6.5最小化安装后启动网卡 2.ifconfig查询IP进行SSH链接 3.更新系统源并且升级系统 4.系统时间更新和设定定时任 5. ...

  6. AudioServicesPlaySystemSound音频服务—b

    对于简单的.无混音音频,AVAudio ToolBox框架提供了一个简单的C语言风格的音频服务.你可以使用AudioservicesPlaySystemSound函数来播放简单的声音.要遵守以下几个规 ...

  7. ssh公钥自动登陆

    第一步,在服务器上安装ssh服务 sudo apt-get install ssh 通过ssh -v查看是否安装成功 第二步创建本地公钥秘钥对 ssh-keygen -t rsa  //创建ssh公钥 ...

  8. SQL查询优化

    在数据库SQL性能优化中,查询优化所占比较高.select调优基本还是比较耗时的.所以我整理了一些提示.每当我在写查询语句的时候,总会看看是否满足这些提示清单. 1.要为WHERE 和JOIN后面的字 ...

  9. 几种开源SIP协议栈对比OPAL,VOCAL,sipX,ReSIProcate,oSIP

    随着VoIP和NGN技术的发展,H.323时代即将过渡到SIP时代,在H.323的开源协议栈中,Openh323占统治地位,它把一个复杂而又先进 的H.323协议栈展现在普通程序员的眼前,为H.323 ...

  10. HDU-5504(逻辑if-else大水题)

    Problem Description You are given a sequence of N integers. You should choose some numbers(at least ...