nodejs实现数据流传输demo

Nodejs评论646阅读模式
摘要

nodejs实现数据流传输demo,分为服务端(接受数据)和客户端(发送数据)。

server端代码

var http=require("http");
var querystring = require('querystring');
​
var server=new http.Server();
console.log("start------");
​
let datastr = "";
​
server.on("request",function(req,res){
    console.log("server on start")
    res.writeHead(200,{
        "content-type":"text/plain"
   });
​
    req.on('data',function(data){
        datastr += data;
        console.log("req.on data:",data.toString());
   });
    //数据全部到达(一次)
    req.on('end',function(){
        // var postStr = datastr;
        console.log("req.on end:",datastr.toString());
        datastr = "";
​
   });
    // res.write("hello nodejs");
    // res.end();
});
console.log("end------");
server.listen(60003);
// server.

client端代码

var http=require("http");
var querystring = require("querystring");
var stringRandom = require('string-random');
var async = require('async');
var tamplateDataOfOBD =({
​
   datanum:0,
   timeStamp:0,
   odbid:0,
   tirepressure:0,
   distance:0,
   carspeed:0,
   enginespeed:0,
   gasremain:0,
   enginetemperature:0,
   waterbox:0,
   localtion:0,
});
​
var optionsPost={
   hostname:"127.0.0.1",
   port:60003,
   method:"POST",
   headers:{}
}
​
​
let count = 0;
​
async.whilst(
   function(){return count < 100;},
   function(cb){
​
       var req = http.request(optionsPost,function(res){
           res.on("data",function(chunk){
               console.log("received chunck:",chunk.toString());
           });
           res.on("end",function(){
               console.log("### end ##");
           });
           console.log("res.statusCode:",res.statusCode);
       });
​
       req.on("error",function(err){
           console.log(err.message);
       });
​
       tamplateDataOfOBD.datanum = count;
       tamplateDataOfOBD.timeStamp = new Date();
       tamplateDataOfOBD.odbid = 'X888888-S666';
       tamplateDataOfOBD.tirepressure = stringRandom(4, {letters: false});
       tamplateDataOfOBD.distance = stringRandom(4, {letters: false});
       tamplateDataOfOBD.carspeed = stringRandom(4, {letters: false});
       tamplateDataOfOBD.enginespeed = stringRandom(4, {letters: false});
       tamplateDataOfOBD.gasremain = stringRandom(4, {letters: false});
       tamplateDataOfOBD.enginetemperature = stringRandom(4, {letters: false});
       tamplateDataOfOBD.waterbox = stringRandom(4, {letters: false});
       tamplateDataOfOBD.localtion = stringRandom(4, {letters: false});
       console.log(tamplateDataOfOBD);
       req.write(JSON.stringify(tamplateDataOfOBD));
       if(count === 10){
           req.end();
       }
       count++;
       setTimeout(cb, 100);
   },
   function(err){
       console.log(err);
   }
);

Nodejs最后更新:2020-11-6