zoukankan      html  css  js  c++  java
  • socket.io技术学习记录

    一、服务端

    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);
    });
  • 相关阅读:
    推自己的镜像到网易云
    supervisord常见问题
    supervisord的配置
    一文解读SDN (转)
    一文解读ZooKeeper (转)
    使用 Docker 和 Nginx 打造高性能的二维码服务 (转)
    一文解读Docker (转)
    一文解读分布式架构 (转)
    一文解读分布式事务 (转)
    一文读懂工业大数据 (转)
  • 原文地址:https://www.cnblogs.com/end-emptiness/p/9341679.html
Copyright © 2011-2022 走看看