Nodejs核心模块之net和http的使用详解

所属分类: 网络编程 / JavaScript 阅读数: 608
收藏 0 赞 0 分享

前言

net和http模块都是node核心模块之一,他们都可以搭建自己的服务端和客户端,以响应请求和发送请求。

net模块服务端/客户端

这里写的net模块是基于tcp协议的服务端和客户端,用到net.createServer和net.connect实现的一个简单请求与响应的demo。

//tcp服务端
var net = require('net')
var sever=net.createServer(function(connection){
  //客户端关闭连接执行的事件
 connection.on('end',function(){
  //  console.log('客户端关闭连接')
 })
 connection.on('data',function(data){
  console.log('服务端:收到客户端发送数据为'+data.toString())
})
//给客户端响应的数据
 connection.write('response hello')
})
sever.listen(8080,function(){
  // console.log('监听端口')
})

//tcp客户端
var net = require('net')
var client = net.connect({port:8080},function(){
  // console.log("连接到服务器")
})
//客户端收到服务端执行的事件
client.on('data',function(data){
  console.log('客户端:收到服务端响应数据为'+data.toString())
  client.end()
})
//给服务端传递的数据
client.write('hello')
client.on('end',function(){
  // console.log('断开与服务器的连接')
})

运行结果

http模块四种请求类型

http服务端:

http.createServer创建了一个http.Server实例,将一个函数作为HTTP请求处理函数。这个函数接受两个参数,分别是请求对象(req)处理请求的一些信息和响应对象(res)处理响应的数据。

//http服务端
const http = require("http");
var fs = require("fs");
var url = require('url')

http.createServer(function (req, res) {
  var urlPath = url.parse(req.url);
  var meth = req.method
  //urlPath.pathname 获取及设置URL的路径(path)部分
  //meth 获取请求数据的方法,一个路径只能被一种方法请求,其他方法请求时返回404
  if (urlPath.pathname === '/' && meth === 'GET') {
    res.write(' get ok');
  } else if (urlPath.pathname === '/users' && meth === 'POST') {
    res.writeHead(200, {
      'content-type': 'text/html;charset=utf-8'
    });
    fs.readFile('user.json', function (err, data) {
      if (err) {
        return console.error(err);
      }
      var data = data.toString();
      // 返回数据
      res.write(data);
    });
  } else if (urlPath.pathname === '/list' && meth === 'PUT') {
    res.write('put ok');
  } else if (urlPath.pathname === '/detail' && meth === 'DELETE') {
    res.write(' delete ok');
  } else {
    res.writeHead(404, {
      'content-type': 'text/html;charset=utf-8'
    });
    res.write('404')
  }
  res.on('data', function (data) {
    console.log(data.toString())
  })

}).listen(3000, function () {
  console.log("server start 3000");
});

http客户端:

http模块提供了两个创建HTTP客户端的方法http.request和http.get,以向HTTP服务器发起请求。http.get是http.request快捷方法,该方法仅支持GET方式的请求。

http.request(options,callback)方法发起http请求,option是请求的的参数,callback是请求的回掉函数,在请求被响应后执行,它传递一个参数,为http.ClientResponse的实例,处理返回的数据。

options常用的参数如下:

1)host:请求网站的域名或IP地址。
2)port:请求网站的端口,默认80。
3)method:请求方法,默认是GET。
4)path:请求的相对于根的路径,默认是“/”。请求参数应该包含在其中。
5)headers:请求头的内容。

nodejs实现的爬虫其实就可以用http模块创建的客户端向我们要抓取数据的地址发起请求,并拿到响应的数据进行解析。

get

//http客户端
const http = require("http");
// 发送请求的配置
let config = {
  host: "localhost",
  port: 3000,
  path:'/',
  method: "GET",
  headers: {
    a: 1
  }
};
// 创建客户端
let client = http.request(config, function(res) {
  // 接收服务端返回的数据
  let repData='';
  res.on("data", function(data) {
    repData=data.toString()
    console.log(repData)
  });
  res.on("end", function() {
    // console.log(Buffer.concat(arr).toString());
  });
});
// 发送请求
client.end();结束请求,否则服务器将不会收到信息

客户端发起http请求,请求方法为get,服务端收到get请求,匹配路径是首页,响应数据:get ok。

post

//http客户端
var http = require('http');
var querystring = require("querystring");
var contents = querystring.stringify({
  name: "艾利斯提",
  email: "m778941332@163.com",
  address: " chengdu",
});
var options = {
  host: "localhost",
  port: 3000,
  path:"/users",
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": contents.length
  }
};
var req = http.request(options, function (res) {
  res.setEncoding("utf8");
  res.on("data", function (data) {
    console.log(data);
  })
})

req.write(contents);
//结束请求,否则服务器将不会收到信息
req.end(); 
//响应的数据为
{
  "user1" : {
    "name" : "mahesh",
    "password" : "password1",
    "profession" : "teacher",
    "id": 1
  },
  "user2" : {
    "name" : "suresh",
    "password" : "password2",
    "profession" : "librarian",
    "id": 2
  }
 }

客户端发起http请求,请求方法为post,post传递数据,匹配路径是/users,服务器响应请求并返回数据user.json里的内容。

put

//http客户端
const http = require("http");
// 发送请求的配置
let config = {
  host: "localhost",
  port: 3000,
  path:"/list",
  method: "put",
  headers: {
    a: 1
  }
};
// 创建客户端
let client = http.request(config, function(res) {
  // 接收服务端返回的数据
  let repData='';
  res.on("data", function(data) {
    repData=data.toString()
    console.log(repData)
  });
  res.on("end", function() {
    // console.log(Buffer.concat(arr).toString());
  });
});
// 发送请求
client.end();

客户端发起http请求,请求方法为put,服务端收到put请求,匹配路径为/list,响应数据:put ok

delect

//http delete请求客户端
var http = require('http');
var querystring = require("querystring");
var contents = querystring.stringify({
  name: "艾利斯提",
  email: "m778941332@163.com",
  address: " chengdu",
});
var options = {
  host: "localhost",
  port: 3000,
  path:'/detail',
  method: "DELETE",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": contents.length
  }
};
var req = http.request(options, function (res) {
  res.setEncoding("utf8");
  res.on("data", function (data) {
    console.log(data);
  })
})

req.write(contents);
req.end();

服务端收到delete请求,匹配路径为/detail,响应数据:delete ok

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

jQuery LigerUI 使用教程表格篇(1)

ligerGrid是ligerui系列插件的核心控件,用户可以快速地创建一个美观,而且功能强大的表格,支持排序、分页、多表头、固定列等等
收藏 0 赞 0 分享

JavaScript中常用的运算符小结

JavaScript中常用的运算符小结,需要的朋友可以参考下。
收藏 0 赞 0 分享

深入理解JavaScript系列(13) This? Yes,this!

在这篇文章里,我们将讨论跟执行上下文直接相关的更多细节。讨论的主题就是this关键字。实践证明,这个主题很难,在不同执行上下文中this的确定经常会发生问题
收藏 0 赞 0 分享

javascript (用setTimeout而非setInterval)

javascript (用setTimeout而非setInterval)如果用setInterval 可能出现 下次调用会在前一次调用前调用
收藏 0 赞 0 分享

JavaScript中两个感叹号的作用说明

用两个感叹号的作用就在于,如果明确设置了o中flag的值(非null/undefined/0""/等值),自然test就会取跟o.flag一样的值;如果没有设置,test就会默认为false,而不是null或undefined
收藏 0 赞 0 分享

javascript写的简单的计算器,内容很多,方法实用,推荐

最近用javascript写了一个简单的计算器,自己测试感觉还好,代码都给了注释,非常不错,推荐大家学习。
收藏 0 赞 0 分享

js的表单操作 简单计算器

javascript写的简单的加减乘除计算器,里面涉及到一些方法还是很实用的哦,新手不要错过
收藏 0 赞 0 分享

Jquery中删除元素的实现代码

empty用来删除指定元素的子元素,remove用来删除元素,或者设定细化条件执行删除
收藏 0 赞 0 分享

javaScript 利用闭包模拟对象的私有属性

JavaScript缺少块级作用域,没有private修饰符,但它具有函数作用域。作用域的好处是内部函数可以访问它们的外部函数的参数和变量(除了this和argument
收藏 0 赞 0 分享

为JavaScript类型增加方法的实现代码(增加功能)

大家在js开发过程中有些功能已经满足不了我们的需求,或没有我们需要的功能,那么我们就可以自己扩展下,个性化js
收藏 0 赞 0 分享
查看更多