Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7202451
  • 博文数量: 510
  • 博客积分: 12019
  • 博客等级: 上将
  • 技术积分: 6836
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-01 16:46
文章分类

全部博文(510)

文章存档

2022年(2)

2021年(6)

2020年(59)

2019年(4)

2018年(10)

2017年(5)

2016年(2)

2015年(4)

2014年(4)

2013年(16)

2012年(47)

2011年(65)

2010年(46)

2009年(34)

2008年(52)

2007年(52)

2006年(80)

2005年(22)

分类: Web开发

2013-10-21 12:00:15

使用nodejs,采用express是一个很好的选择,也可自己采用http库直接实现。该列子通过简单的事件,把数据粘起来,从而能应对post模式中大数据传输的要求。


点击(此处)折叠或打开

  1. var http = require('http');
  2. var url = require('url');


  3. function test1(receiveBuf, res){
  4.     //do something
  5.     res.end('====>set ok Hello World 1\n');
  6. }

  7. function test2(receiveBuf,res){
  8.     //do something
  9.     res.end('====>set ok Hello World 2 \n');
  10. }

  11. var PATH_MAP = {};
  12. PATH_MAP["/ydsdk_call.php"] = test1;
  13. PATH_MAP["/ydsdk_get.php"] = test22;

  14. var Server = http.createServer(function (req, res) {
  15.     var receiveBuf = '';
  16.             
  17.     //url.parse(req.url).pathname; //建议自己实现解析,url.parse函数性能低
  18.     var pathname = url.parse(req.url).pathname;
  19.     var fun = PATH_MAP[pathname];
  20.     if (typeof(fun)=="undefined" || fun==null) {
  21.           return ;
  22.     }

  23.     req.setEncoding('utf8');
  24.     
  25.     req.addListener('data', function(Data) {
  26.         receiveBuf += Data;
  27.     });
  28.         
  29.     res.writeHead(200, {'Content-Type': 'text/plain'});
  30.     

  31.     res.on("close",function(){
  32.         console.log("res closed");
  33.     });
  34.     
  35.     req.on("close",function(){
  36.              console.log("req closed");
  37.     });
  38.     
  39.             
  40.     req.addListener('end', function() {
  41.              fun(receiveBuf,res);
  42.     });

  43.    
  44. });

  45. Server.listen(8082, '172.28.14.218',1024);


  46. Server.setTimeout(60000,function(cli){
  47.         cli.end('timeout\n');
  48. });
关于上面列子,可满足较高并发。若提高并发访问要注意3点:
1)优化系统,centos下主要是sysctl.conf;
2)提高cpu,因为nodejs的弱点就是cpu密集;
3)js脚本编写要注意效率,主要要注意时间复杂度,复杂算法尽量用c实现。


阅读(10021) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~