Nodejs 服務器端與客戶端之間的操做 node
這是一個小的程序引用。經過客服端執行程序。服務端接受程序並打印文本web
服務器端 Server.js 服務器
//nodejs Serverweb服務器 var qs = require('querystring'); require('http').createServer(function(req,res){ var body =''; //獲取數值 req.on('data',function(chunk){ body += chunk; }); req.on('end',function(){ res.writeHead(200); res.end('Done'); //打印輸出文本! console.log('\n 獲得名字 : \033[90m' + qs.parse(body).name + '\033[39m\n'); }); }).listen(3000);
客戶端 client.js ui
//客戶端 var http =require('http'), qs = require('querystring') function send(thename){ http.request({ host:'127.0.0.1', port:3000, url:'/', method:'POST' },function(res){ res.setEncoding('utf8'); res.on('end',function(){ console.log('\n 獲得名字 : \033[90m request \033[39m\n'); process.stdout.write('\n 你的名字: '); }); }).end(qs.stringify({name:thename})); //數據是經過end方法發送的 } //stdout 是讀,stdin 是寫 process.stdout.write('\n 你的名字: '); process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data',function(name){ send(name.replace('\n','')); });
效果圖:
url