美文网首页Node
Express+Socket.io实时投票系统(三)

Express+Socket.io实时投票系统(三)

作者: kangkangz4 | 来源:发表于2016-10-27 17:20 被阅读124次

    第三节,接上面的二节,这里我们加入socket.io的处理
    首先,我们在./bin/www文件里加入

    var routes = require('../routes/index');
    
    var server = http.createServer(app);
    //在server下加入socket.io的方法
    /**
     * Create WebSocket server
     */
    var io = require('socket.io').listen(server);
    io.sockets.on('connection', routes.vote);
    

    这里我们加入了socket的监听,并把socket的监听交给routes.vote来处理,在route/index.js中加入

    router.vote = function(socket){
        socket.on('send:vote', function(data){
            var ip = socket.handshake.headers['x-forwarded-for'] || socket.handshake.address;
            //查找当前投票
            Poll.findById(data.poll_id, function(error, poll){
                var choice = poll.choices.id(data.choice);
                choice.votes.push({ip: ip});
                poll.save(function(error, doc){
                    var theDoc = {
                        question: doc.question, 
                        _id: doc._id, 
                        choices: doc.choices,
                        userVoted: false, 
                        totalVotes: 0
                    };
                    //查询当前IP是否已经投过票
                    poll.choices.forEach(function(choice, index) {
                        choice.votes.forEach(function(vote, index) {
                            theDoc.totalVotes++;
                            theDoc.ip = ip;
                            if(vote.ip === ip){
                                theDoc.userVoted = true;
                                theDoc.userChoice = { _id: choice._id, text: choice.text };
                            }
                        });
                    });
    
                    socket.emit('myvote', theDoc);
                    socket.broadcast.emit('vote', theDoc);
                });
            });
        });
    };
    

    好了,服务端的处理完成了。
    在public/js/services/services.js中加入

    //webSocket定义
    .factory('socket', function($rootScope){
        var socket = io.connect();
        return {
            on: function(eventName, callback){
                socket.on(eventName, function(){
                    var args = arguments;
                    $rootScope.$apply(function(){
                        callback.apply(socket, args);
                    });
                });
            },
            emit: function(eventName, data, callback){
                socket.emit(eventName, data, function(){
                    var args = arguments;
                    $rootScope.$apply(function(){
                        if(callback){
                            callback.apply(socket, args);
                        }
                    });
                });
            }
        }
    });
    

    public/js/controllers/controllers.js中加入

    //投票详情
    .controller('PollItemCtrl', function($scope, $routeParams, socket, Poll){
        Poll.get($routeParams.pollId).then(function(data){
            $scope.poll = data;
        })
        //监听当前用户
        socket.on('myvote', function(data){
            console.dir(data);
            if(data._id === $routeParams.pollId){
                $scope.poll = data;
            }
        });
        //监听投票后的数据
        socket.on('vote', function(data){
            console.dir(data);
            if(data._id === $routeParams.pollId){
                $scope.poll.choices = data.choices;
                $scope.poll.totalVotes = data.totalVotes;
            }
        });
        //投票
        $scope.vote = function(){
            var pollId = $scope.poll._id,
                choiceId = $scope.poll.userVote;
            if(choiceId){
                var voteObj = {
                    poll_id : pollId,
                    choice: choiceId
                }
                socket.emit('send:vote', voteObj);
            }else{
                alert('请选择一个选项');
            }
        };
    })
    

    这里是客户端的处理,以上就是全部代码了
    工程地址已经上传到GitHub上了
    可以通过以下地址查看或下载
    代码查看

    相关文章

      网友评论

        本文标题:Express+Socket.io实时投票系统(三)

        本文链接:https://www.haomeiwen.com/subject/avksuttx.html