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();

});

【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. C++中getline函数的使用

    代码: #include <iostream> #include <cstdio> using namespace std; int main(){ char* s; s = ...

  2. POJ 3254 状压DP

    题目大意: 一个农民有一片n行m列 的农场   n和m 范围[1,12]  对于每一块土地 ,1代表可以种地,0代表不能种. 因为农夫要种草喂牛,牛吃草不能挨着,所以农夫种菜的每一块都不能有公共边. ...

  3. C程序设计语言练习题1-19

    练习1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来.使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序.代码如下: #include <stdio.h> // ...

  4. 关于Cococs中的CCActionEase

    尊重作者劳动,转载时请标明文章出处.作者:Bugs Bunny地址:http://www.cnblogs.com/cocos2d-x/archive/2012/03/13/2393898.html 本 ...

  5. iOS开发——C篇&预处理

    其实在C语言的远行过程中,有这样一个流程, 编译:C----〉可执行文件(可以运行的) 1:.C------.i 预处理(之前和之后还是C语法)2: .i-------.s 编译(之前是C语法,之后是 ...

  6. 转:iOS 7人机界面准则

    原文来自于:http://www.infoq.com/cn/news/2014/02/ios-ui-design Apple官方推出的“iOS人机界面准则”一直被iOS开发者奉为绝对的设计参考宝典,特 ...

  7. CreateLiveCMSV4.0 漏洞,无需后台Get shell

    Title:CreateLiveCMSV4.0 漏洞,无需后台Get shell --2012-03-06 17:28 标题:CreateLive CMS Version 4.0.1006 漏洞,无需 ...

  8. android EditText内嵌图片

    如下所示: 主要用到的属性:android:drawableLeft <EditText android:layout_width="match_parent" androi ...

  9. 基础 ADO.NET 访问MYSQL 与 MSSQL 数据库例子

    虽然实际开发时都是用 Entity 了,但是基础还是要掌握和复习的 ^^ //set connection string, server,database,username,password MySq ...

  10. Entity Framework with MySQL 学习笔记一(关系)

    这一篇说说 EF Fluent API 和 DataAnnotations 参考 : http://msdn.microsoft.com/en-us/data/jj591617.aspx http:/ ...