注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

星期五

明天不上班

 
 
 

日志

 
 
关于我

一个特立独行的Java程序员,比较宅,上上网,写博客,听音乐,看电影。

网易考拉推荐

NodeJS+WebSocket+FusionWeights(3)  

2012-05-27 13:33:26|  分类: Nodejs |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
由于上次的实现,已经不能工作,所以基于新的WebSocket协议重新实现上次的例子:http://zhenghaoju700.blog.163.com/blog/static/1358595182011521113324490/
环境:
Node v0.6.12
npm  1.1.4
OS Ubuntu12.04
Chrome Version 19.0.1084.46

使用WebSocket-node模块 https://github.com/Worlize/WebSocket-Node
npm install websocket


server.js

var http = require("http")
,fs = require("fs")
,path = require("path")
,url = require("url")
,WebSocketServer = require('websocket').server;

var spawn = require('child_process').spawn;
var iostat = spawn("iostat",["-c","2"]);

var httpServer = http.createServer(function(req, res){
//handle http request for static file
staticFileServer(req,res);
});

httpServer.listen(8080, function() {
console.log((new Date()) + 'Http Server is listening on port 8080');
});

wsServer = new WebSocketServer({
httpServer: httpServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});

function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}

wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');

iostat.stdout.on('data',function(data) {
console.log((new Date()) + 'Send date: ' + data);
connection.send('' + data);
});

connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});


var handler404 = function(req, res){
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Page Not Found');
};


var staticFileServer = function(req, res, filePath){
if(!filePath){
filePath = path.join(__dirname, url.parse(req.url).pathname);
}
path.exists(filePath, function(exists) {
if(!exists) {
handler404(req, res);
return;
}

fs.readFile(filePath, "binary", function(err, file) {
var ext = path.extname(filePath);
ext = ext ? ext.slice(1) : 'html';
res.writeHead(200, {'Content-Type': contentTypes[ext] || 'text/html'});
res.write(file, "binary");
res.end();
});
});
};

chart.html

<!DOCTYPE html>
<html>
<head>
<title>WebSocket & Node.JS Test Page</title>
<style>
#iostat {
width: 500px;
height: 300px;
overflow-y: auto;
background-color: black;
color: white;
padding-left: 30px;
margin: 0,auto;
}
</style>
<script type="text/javascript" src="http://zhenghaoju700.blog.163.com/blog/./chart/FusionCharts.js"></script>
</head>
<body>
<div id="chartdiv"></div>
<div id="iostat"></div>
<script>

var chart = new FusionCharts("./chart/RealTimeLine.swf","chartId","530","350","0","1");
chart.setDataURL("./chart/Data.xml");
chart.render("chartdiv");

var hostname = "127.0.0.1";
var port = 8080;
var url = "ws://"+hostname+":"+port;
w = new WebSocket(url,'echo-protocol');

w.onopen = function() {
}
w.onmessage = function(e) {
var msg = e.data;
var ms = msg.split("%idle");
msg = ms.join("%idle <br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
var iostat = document.getElementById("iostat");
var p = document.createElement("p");
p.innerHTML = msg;
iostat.appendChild(p);
iostat.scrollTop = iostat.scrollHeight;

var chartRef = getChartFromId("chartId");
var currDate = new Date();
var label = currDate.getHours() + ":" + currDate.getMinutes() + ":" + currDate.getSeconds();
var dataStr = ms[1];
var datas = dataStr.split(/\s+/);

//Build data string in format &label=...&value=...
var strData = "&label=" + label + "&value=" + datas[1] + "|" + datas[2] + "|" + datas[3] + "|" + datas[4]+ "|" + datas[5]+ "|" + datas[6]+ "|" + datas[7];
chartRef.feedData(strData);
}

w.onclose = function(e) {
}
</script>
</body>
</html>

运行:
NodeJS+WebSocket+FusionWeights(3) - 星期五 - 星期五
 
Data.xml

<chart caption='CPU Monitor' numberPrefix='%' setAdaptiveYMin='1' xAxisName='Time' showRealTimeValue='1'

realTimeValuePadding='50' labelDisplay='Rotate' slantLabels='1' >
<categories>
</categories>
<dataset seriesName='%user' showValues='0'>
</dataset>
<dataset seriesName='%nice' showValues='0'>
</dataset>
<dataset seriesName='%system' showValues='0'>
</dataset>
<dataset seriesName='%iowait' showValues='0'>
</dataset>
<dataset seriesName='%steal' showValues='0'>
</dataset>
<dataset seriesName='%idle' showValues='0'>
</dataset>

<styles>
<definition>
<style type='font' name='captionFont' size='14' />
</definition>
<application>
<apply toObject='Caption' styles='captionFont' />
<apply toObject='Realtimevalue' styles='captionFont' />
</application>
</styles>
</chart>

  评论这张
 
阅读(1137)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017