global.messages={//'resid':[]};varchar500=(function(){vari=0;vararr=[];for(i=0;i<500;i++){arr.push(' ');}returnarr.join('');})();varhttp_method_funs={'GET':function(resid,data,request,response){if(global.messages[resid]==undefined){global.messages[resid]=[];}response.writeHead(200,{'content-type':'text/plain'});varinterval=setInterval(myoutput,500);response.connection.on('end',function(){console.log("GET\t"+resid+"\tclosed");clearInterval(interval);});myoutput();functionmyoutput(){varmsgs=global.messages[resid];if(msgs.length){varstr=msgs.join("\n\n\n")+"\n\n\n";str=(str.length<500)?(str+char500):str;//for MTUresponse.write(str);global.messages[resid]=[];}}},'PUT':function(resid,data,request,response){if(global.messages[resid]==undefined){global.messages[resid]=[];}global.messages[resid].push(data);console.log(global.messages);response.writeHead(200,{'content-type':'text/plain'});response.end('ok\n');},};//method function require('http').createServer(function(request,response){varurlinfo=require('url').parse(request.url);varresid=urlinfo['pathname'];vardata=(urlinfo['query'])?urlinfo['query']:0;varmethod=request.method;console.log(method+"\t"+resid);if(typeofhttp_method_funs[method]=='function'){http_method_funs[method].call(null,resid,data,request,response);}else{response.writeHead(400);response.end("unsupport method\n");}}).listen(18124);console.log('server running at http://127.0.0.1:18124/');
h3. 测试方法
上面的代码保存到文件, 我们在第一个终端启动这个服务:
shell> node hello.js
我们在第二个终端模拟iframe的数据流. 输入命令, 观察收到的数据:
telnet 127.0.0.1 18124
GET /mymessages HTTP/1.1
HTTP/1.1 200 OK
content-type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked
我们在第三个终端输入curl -X PUT命令, 模拟发送两条消息:
shell> curl -X PUT "http://127.0.0.1:18124/mymessages?a=1&b=2&c=3"
ok
shell> curl -X PUT "http://127.0.0.1:18124/mymessages?a=4&b=5&c=6"
ok