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. switch case加条件语句(非等值) php

    <?php $s_level=rand(1,6); echo $s_level.'<br/>'; switch(true){ case $s_level<3 : echo 'l ...

  2. explode 结合 str_replace对获取的URL处理手记

    今天更新我的一个FKQQ的程序.我的一个PHP文件接收到HQ的QQ号码的字符串.因为获取的内容有大量的垃圾内容所以我用str_replace做了一个处理代码如下: $xx1 = preg_replac ...

  3. eclipse中myBatis引入

    1.添加config.xml配置文件 2.定义与数据库的数据实体映射类 3.创建操作表的是sql映射文件 即:mapper.xml 4.在配置文件config.xml中注册sql映射文件(步骤三创建的 ...

  4. Linux C判断日期格式是否合法

    Title:Linux C判断日期格式是否合法 --2013-10-11 11:54 #include <string.h> // strlen() , strncpy() #includ ...

  5. Boost编程之获取可执行文件的当前路径

    #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> std::str ...

  6. Android中如何利用attrs和styles定义控件

    一直有个问题就是,Android中是如何通过布局文件,就能实现控件效果的不同呢?比如在布局文件中,我设置了一个TextView,给它设置了 textColor,它就能够改变这个TextView的文本的 ...

  7. yiic模块module使用

    模块是一个独立的软件单元,它包含 模型, 视图, 控制器 和其他支持的组件. 在许多方面上,模块看起来像一个 应用.主要的区别就是模块不能单独部署,它必须存在于一个应用里. 用户可以像他们访问普通应用 ...

  8. rsyslog 直接kill进程,在重新启动会全部发送日志

    <pre name="code" class="html">jrhapt11:/root# ps -ef | grep rsyslog root 8 ...

  9. BZOJ2091: [Poi2010]The Minima Game

    2091: [Poi2010]The Minima Game Time Limit: 10 Sec  Memory Limit: 259 MBSubmit: 243  Solved: 163[Subm ...

  10. 32G sd卡格式化成fat

    fat文件系统格式只支持4G及以下的内存空间的存储设备,对于4G及以上的存储设备可以使用fat32或ntfs文件系统,建议使用ntfs文件系统,这样可以最有效地利用存储设备的存储空间,而且可以减少出现 ...