<
NodeJs 扩展功能
>
上一篇

html-css学习
下一篇

NodeJs 核心模块使用

第七天

  1. nodejs http服务优化
  2. 简易版socket聊天室搭建

nodejs 搭建http服务,并了解form的GET和POST提交,分析了解服务端request与response及url和querystring的搭配使用

代码实现:

server.js

var http = require('http');
var doGet = require('./doGet');
var doPost = require('./doPost');
var httpServer = http.createServer(function(req,res) {
  if(req.method == "GET") {
    doGet.doGet(req,res);
  } else if(req.method == "POST") {
    doPost.doPost(req,res);
  } else {
    res.writeHead(404);
    res.end();
  }
}).listen(8080);

doGet.js

function doGet(req, res) {
  res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'});
  res.write("<html>");
  res.write("<head>");
  res.write("<title>");
  res.write("</title>");
  res.write("</head>");
  res.write("<body>");
  res.write("<form method='POST'>");
  res.write("账号:<input type='text' name='username'>密码:<input type='password' name='password'><input type='submit' value='提交'>");
  res.write("</form>");
  res.write("</body>");
  res.write("</html>");
  res.end();
}
module.exports = {
  doGet:doGet
}

doPost.js

var queryString = require('querystring');
function doPost(req, res) {
  var result = '';
  req.on('data', (chunk) => {
    result += chunk.toString();
  })
  req.on('end', () => {
    res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
    var query = queryString.parse(result);
    res.write(query.username + "\n" + query.password);
    res.end();
  });
}

module.exports = {
  doPost:doPost
}

简易版Socket聊天室

  1. 创建服务端socket 并进行通信 且结束
  2. 创建客户端socket 并进行通信 且结束
  3. 服务端取消结束,加入回应客户端信息代码
  4. 客户端取消结束,加入连续发送消息给客户消息的功能
  5. 服务端增加socket列表组,记录所有连接的用户信息
  6. 服务端需要解决用户端强制退出的问题

server.js

var net = require('net');
var socketList = [];
var server = net.createServer((socket) => {
  socketList.push(socket);
	socket.on('data', (data) => {
    sendData(data);
  });
  socket.on('end', () => {
    //TODO 需要把当前socket在socketList中排除,否则会发信息报错
    socket.end();
  });
}).listen(8080, 1773, ()=>{
  console.log('connection success');
});

client.js

var net = require('net');
var hostname = process.argv[2];
var port = process.argv[3];
var client = net.createConnection({host:hostname port:port}, () => {
  console.log('connected server success');
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
    let chunk;
    while((chunk = process.stdin.read()) !== null) {
      client.write('data:' + chunk);
    }
  });
});

client.on('error', (err) => {
  console.log(err);
});

client.on('data', (data) => {
  console.log(data.toString());
});

client.on('end', () => {
  console.log('disConnection success');
});
Top
Foot