一、服务端
var express = require('express');
var app = require('express')();
var http = require('http').Server(app); //建立服务器
//在相应的服务器上建立通信,当然,http服务器也可以,获取方法有差异
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
//获取数据
socket.on('score', function(score){
var data = score.split('&');
var upuserid = data[0].split('=')[1];
var upscore = parseInt(data[1].split('=')[1]);
for(var i in user) {
if(user[i].userid == upuserid) {
user[i].score = Math.max(upscore,user[i].score);
Update(mysql, upuserid, Math.max(upscore,user[i].score));
break;
}
}
for(var i = user.length - 1; i > 0; i --) {
if(user[i].score > user[i-1].score) {
var tmp = user[i];
user[i] = user[i-1];
user[i-1] = tmp;
}
}
//发送数据
io.emit('userlist2', user);
});
});
二、客户端
//一启动就开启,实时读取数据
socket.on('userlist2', function(msg){
userlist = msg;
console.log(userlist[0]);
(function($){
var text = "<table>
" +
" <thead>
" +
" <tr>
" +
" <th width="50%">用户</th>
" +
" <th width="50%">分数</th>
" +
" </tr>
" +
" </thead>
" +
" <tbody id="userscore">
" +
" </tbody>
" +
" </table>";
document.getElementById("scorelist").innerHTML = text;
var $tbody = $("#userscore");
document.getElementById("userscore").innerHTML = "";
for ( var i in userlist) {
var $item = $("<tr><td>"+userlist[i].userid+"</td><td>"+userlist[i].score+"</td></tr>");
if(userlist[i].userid == userid) {
$item = $("<tr style='background: rgba(255,0,0,0.3);'><td>"+userlist[i].userid+"</td><td>"+userlist[i].score+"</td></tr>");
}
$tbody.append($item);
}
})(jq172);
});