123.js `` $(function () {
$(document).ready(function () {
var sensordata = 0;
var socket = io.connect();
socket.on('data', function (obj) {//接收到服务器发送过来的名为'new'的数据
sensordata = boj.dataname;
//console.log(obj.dataname);//data为应服务器发送过来的数据。
//socket.emit('my new event', { my:'new data' });//向服务器发送数据,实现双向数据传输
});
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = sensordata;
//y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
index.js
var express=require(‘express’);
var app=express();
var http=require(‘http’).Server(app);
var io=require(‘socket.io’)(http);
var dgram = require(‘dgram’);
var server = dgram.createSocket(‘udp4’);
http.listen(3000, function () { console.log(‘Server listening at port %d’, 3000); });
app.get(’/’,function(req,res){ res.sendFile(__dirname+’/123.html’); });
server.on(‘message’, function(msg, rinfo) { console.log(‘服务端获取信息:’+msg+‘来自:’+rinfo.address+’:’+rinfo.port); io.sockets.emit(‘data’,{ dataname:msg }); });
server.on(‘listening’, function() { var address = server.address(); console.log(‘服务端正在监听:’+address.address+’:’+address.port); });
server.bind(7);
123.html
</head>
<body>
<div id="container" style="min-width:400px;height:400px"></div>
<script src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
<script src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>
<script src="123.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</body>
</html>
``