Socket
服务端:
const express = require('express');
var http = require('http');
const app = express();
const server = http.createServer(app);
const config = require('../config');
const path = require('path');
const io = require('socket.io')(server, {
path: config.root ? (config.root + "/socket.io") : null
});
var sockets = {};
// app.use(express.static(__dirname));
app.use(express.static(__dirname + '/../../public'));
// app.use(config.root, express.static(__dirname + '/../public'));
io.on('connection', function(socket) {
// connCount++;
console.log('connect!!!');
sockets[socket.id] = socket;
socket.on('monitorData', function(order) {
let kind = order.kind;
// delete order.kind;
console.log('monitorData!!!');
monitorData(socket.id, kind, order);
});
socket.on('clearMonitor', function(kind) {
console.log('clearMonitor!!!');
clearMonitor(socket.id, kind);
});
socket.on('disconnect', function() {
console.log('disconnect!!!');
clearMonitor(socket.id);
delete sockets[socket.id];
// connCount--;
});
});
setInterval(function(){
sendToAll();
},5000);
monitorData = function(id,kind,data){
var socket = sockets[id];
if(data){
data['server'] = 'come from server';
}
socket.emit('data', data||{'datas':'test monitorData'});
}
clearMonitor = function(id){
var socket = sockets[id];
socket.emit('clear', 'clear data');
}
sendToAll = function(){
for(var id in sockets){
// var socket = sockets[id];
monitorData(id,{datas:'to all'});
}
}
server.listen(config.port, '0.0.0.0');
Client端:
<!DOCTYPE html>
<html>
<head>
<title>arc</title>
<!-- <link rel="stylesheet" href='../css/newui.css'> -->
<!-- <link rel="stylesheet" href="../font/iconfont.css"> -->
<script>
// if (!window.it) {
// window.it = {};
// }
// if (!window.make) {
// window.make = {};
// }
</script>
<script src="../libs/jquery.js"></script>
<script src="../libs/jquery-ui.min.js"></script>
<!-- // <script src="../component/arc.js"></script> -->
<script type="text/javascript" src="../libs/socket.io.js"></script>
</head>
<style>
html body{
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
position: absolute;
}
.arc {
position: absolute;
top: 200px;
left: 200px;
}
.point {
position: absolute;
top: 65px;
left: 65px;
width:270px;
height:270px;
background-color: rgba(255,255, 20,0.5);
border-radius: 50%
}
</style>
<script>
$(function() {
// $('.arc').arc();
// var angle = 0;
var path = '/socket.io';
var origin = window.location.origin;
var socket = window.socket = io.connect(origin, {
path: path
});
socket.on('data', function(data) { //增加
console.log('---------推送数据: ' + JSON.stringify(data));
});
socket.on('clear', function(data) { //增加
console.log('---------推送数据: ' + JSON.stringify(data));
});
setInterval(function() {
// angle += 1;
socket.emit('monitorData',{});
// $('.arc').arc('option', 'rotate', angle);
}, 2000)
})
</script>
<body>
</body>
</html>