【nodejs学习】2.网络相关
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.网络相关的更多相关文章
- NodeJS学习之网络操作
NodeJS -- 网络操作 使用NodeJS内置的http模块简单实现HTTP服务器 var http = require('http'); http.createServer(function(r ...
- 七天学会NodeJS (原生NodeJS 学习资料 来自淘宝技术团队)
NodeJS基础 什么是NodeJS JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器. ...
- NodeJS学习指南
七天学会NodeJS NodeJS基础 什么是NodeJS 有啥用处 如何安装 安装程序 编译安装 如何运行 权限问题 模块 require exports module 模块初始化 主模块 完整示例 ...
- NodeJS 学习笔记一
他创造NodeJS的目的是为了实现高性能Web服务器,他首先看重的是事件机制和异步IO模型的优越性,而不是JS.但是他需要选择一种编程语言实现他的想法,这种编程语言不能自带IO功能,并且需要能良好支持 ...
- Nodejs学习笔记(十六)--- Pomelo介绍&入门
目录 前言&介绍 安装Pomelo 创建项目并启动 创建项目 项目结构说明 启动 测试连接 聊天服务器 新建gate和chat服务器 配置master.json 配置servers.json ...
- nodejs学习以及SSJS漏洞
0x01 简介 什么是nodejs,it's javascript webserver! JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对 ...
- Nodejs学习笔记(十六)—Pomelo介绍&入门
前言&介绍 Pomelo:一个快速.可扩展.Node.js分布式游戏服务器框架 从三四年前接触Node.js开始就接触到了Pomelo,从Pomelo最初的版本到现在,总的来说网易出品还算不错 ...
- NodeJS学习笔记 进阶 (13)Nodejs进阶:5分钟入门非对称加密用法
个人总结:读完这篇文章需要5分钟,这篇文章讲解了Node.js非对称加密算法的实现. 摘录自网络 地址: https://github.com/chyingp/nodejs-learning-guid ...
- NodeJS学习笔记 进阶 (12)Nodejs进阶:crypto模块之理论篇
个人总结:读完这篇文章需要30分钟,这篇文章讲解了使用Node处理加密算法的基础. 摘选自网络 Nodejs进阶:crypto模块之理论篇 一. 文章概述 互联网时代,网络上的数据量每天都在以惊人的速 ...
- NodeJS学习笔记 进阶 (1)Nodejs进阶:服务端字符编解码&乱码处理(ok)
个人总结:这篇文章主要讲解了Nodejs处理服务器乱码及编码的知识,读完这篇文章需要10分钟. 摘选自网络 写在前面 在web服务端开发中,字符的编解码几乎每天都要打交道.编解码一旦处理不当,就会出现 ...
随机推荐
- centos 6.5网卡dhcp不能获得网关
环境:vmware +centos6.5 添加两个虚拟网卡.一个自动获取ip(用于上网-桥接) 一个手动(与主机通信用于ssh-NAT). 因为自已手动改了一下ifcfg-eth0里面的HWADDR ...
- javascript控制图片等比例缩放
<SCRIPT language="JavaScript"> function DrawImage(ImgD,FitWidth,FitHeight){ var imag ...
- shell脚本实现覆盖写文件和追加写文件
1.覆盖写文件 ">" date > not_append_file.txt
- asp.net core VS goang web[修正篇]
先前写过一篇文章:http://www.cnblogs.com/gengzhe/p/5557789.html,也是asp.net core和golang web的对比,热心的园友提出了几点问题,如下: ...
- node.js相关
node node最大的特点是单线程,因此一个只能有一个任务运行,大量采用异步操作. 某一个任务的后续操作一般采用回调函数的形式 var callback = function (error, val ...
- C#数据类型汇总
通用类型系统 C#中,变量是值还是引用仅取决于数据类型 所有的数据类型都是对象.因为它们具有自己ide方法和属性 int int_value = 101; //调用*int_value*的比较方法与整 ...
- C++中基于Crt的内存泄漏检测(重载new和delete,记录在Map里)
尽管这个概念已经让人说滥了 ,还是想简单记录一下, 以备以后查询. #ifdef _DEBUG#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FIL ...
- windows环境变量如何在cmd中打印
在windows的cmd下,用"set"命令可以得到全部的环境变量,如何想得到某个环境变量,直接这样"set path"就可以了. set不仅如何,还有其他功能 ...
- delphi7开发webservice部属在apache服务器中 转
delphi7开发webservice部属在apache服务器中 delphi7 webservice apache 用Delphi7开发Web Service程序,并把服务程序放在apache We ...
- Android 调用图库选择图片实现和参数详解
//选择图片,调用图库 bt4.setOnClickListener(new OnClickListener() { @Override public void o ...