Thursday, 1 June 2017

Pass username from client side to server side [Node.js/Socket.io/JavaScript]

I'm currently trying to add usernames to my chat which i'm creating with node.js and socket.io

Currently the authentication part is done through passport and it will redirect the user to the dashboard. Now the user could click enter world which will redirect him to the enter.handlebars site.

So I'm rendering the site in the following way:

// Get Site
router.get('/enter', ensureAuthenticated, function(req, res){
    res.render('enter', {username: req.user.username});
});

as you can see I'm passing the username to the client side code which can be accessed by entering:



But I will need this value also in the app.js file (server side code). How could I pass the username from the client side code to the server side code?


Question: Is there a way, to pass it with the socket itself? So I could get the username in here?

Player.onConnect = function(socket)


My current enter.handlebars file code:

<body class="layout-boxed login-cover">
    <!-- Main navbar -->
    <div class="navbar navbar-inverse">
        <div class="navbar-boxed">
            <div class="navbar-header">
                <a class="navbar-brand" href="index.html"><img src="/images/logo_light.png" alt=""></a>

                <ul class="nav navbar-nav visible-xs-block">
                    <li><a data-toggle="collapse" data-target="#navbar-mobile"><i class="icon-tree5"></i></a></li>
                </ul>
            </div>

            <div class="navbar-collapse collapse" id="navbar-mobile">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#">Support</a></li>

                    <li>
                        <a href="#">
                            <i class="icon-cog3"></i>
                            <span class="visible-xs-inline-block position-right">Icon link</span>
                        </a>                        
                    </li>

                    <li class="dropdown dropdown-user">
                        <a class="dropdown-toggle" data-toggle="dropdown">
                            <span></span>
                            <i class="caret"></i>
                        </a>

                        <ul class="dropdown-menu dropdown-menu-right">
                            <li><a href="#"><i class="icon-user-plus"></i> My profile</a></li>
                            <li><a href="#"><i class="icon-coins"></i> My balance</a></li>
                            <li class="divider"></li>
                            <li><a href="#"><i class="icon-cog5"></i> Account settings</a></li>
                            <li><a href="../authenticate.php"><i class="icon-switch2"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /main navbar -->

    <!-- Second navbar -->
    <div class="navbar navbar-default" id="navbar-second">
        <div class="navbar-boxed">
            <ul class="nav navbar-nav no-border visible-xs-block">
                <li><a class="text-center collapsed" data-toggle="collapse" data-target="#navbar-second-toggle"><i class="icon-menu7"></i></a></li>
            </ul>

            <div class="navbar-collapse collapse" id="navbar-second-toggle">
                <ul class="nav navbar-nav">
                    <li><a href="/zworld/dashboard"><i class="icon-display4 position-left"></i> Dashboard</a></li>
                    <li class="active"><a href=""><i class="icon-heart6 position-left"></i> Enter World</a></li>
                    <li><a href=""><i class="icon-user-tie position-left"></i> Wardrobe</a></li>
                    <li><a href=""><i class="icon-price-tag position-left"></i> Store</a></li>
                    <li><a href=""><i class="icon-cart2 position-left"></i> Shop</a></li>
                </ul>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="icon-cash3 position-left"></i> 0 Zbucks</a></li>
                    <li><a href="#"><i class="icon-credit-card2 position-left"></i> 0 Zcard</a></li>
                </ul>
            </div>
        </div>
    </div>
    <!-- /second navbar -->

    <!-- Page container -->
    <div class="page-container">


    <div class="breadcrumb-line breadcrumb-line-component content-group-lg">
                    <ul class="breadcrumb">
                        <li><a href="#"><i class="icon-home2 position-left"></i> Zworld</a></li>
                        <li class="active">Enter World</li>
                    </ul>

                    <ul class="breadcrumb-elements">
                        <li><a href="#"><i class="icon-comment-discussion position-left"></i> Private Messages</a></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                <i class="icon-gear position-left"></i>
                                Actions
                                <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu dropdown-menu-right">
                                <li><a href="#"><i class="icon-inbox pull-right"></i> Action</a></li>
                                <li><a href="#"><i class="icon-googleplus5 pull-right"></i> Another action</a></li>
                                <li><a href="#"><i class="icon-grid-alt pull-right"></i> Something else</a></li>
                                <li class="divider"></li>
                                <li><a href="#"><i class="icon-spinner2 spinner pull-right"></i> One more line</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>

        <!-- Page content -->
        <div class="page-content">

            <div id="chatModal" class="panel panel-default chatModal">
                <div class="panel-heading">
                    <h6 class="panel-title">Zworld Chat</h6>
                    <div class="heading-elements">
                        <ul class="icons-list">
                            <li><a data-action="collapse"></a></li>
                            <li><a data-action="reload"></a></li>
                        </ul>
                    </div>
                </div>

                <div style="overflow-y: scroll; position:relative; height: 200px;" class="panel-body" id="chat-text"></div>
            </div>

            <!-- Main content -->
            <div class="content-wrapper cnt">
                <div class="panel panel-flat" style="height: 700px;">
                    <canvas style="background-color: #eee;" id="ctx"></canvas>

                    <div id="chat" style="width: 100%; height: 46px; background-color: #fff; border-top: 1px solid #ddd; margin-top: -6px;">
                        <div id="subBar_left" style="float:left; width: 80%;">
                            <form id="chat-form">
                                <input id="chat-input" type="text" style="width:100%; padding-left: 10px; height: 46px; border: none;" placeholder="Enter message..." autocomplete="off"></input>
                            </form> 
                        </div>
                        <div class="verticalLine" id="subBar_right" style="float:right; width: 20%; line-height: 46px;">
                            <a class="showChat" style="color: #333333 !important; padding-left: 25px;" data-popup="tooltip" title="Open chatbox" data-placement="bottom">
                                <i class="icon-bubbles10"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Open friendlist" data-placement="bottom">
                                <i class="icon-users"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Open Map" data-placement="bottom">
                                <i class="icon-location4"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Visit room" data-placement="bottom">
                                <i class="icon-home5"></i>
                            </a>
                            <a href="" style="color: #333333 !important; padding-left: 20px;" data-popup="tooltip" title="Report user" data-placement="bottom">
                                <i class="icon-flag3"></i>
                            </a>
                        </div>
                    </div>

                </div>
            </div>
            <!-- /content area -->

        </div>
        <!-- /page content -->

    </div>
    <!-- /page container -->

    <!-- Footer -->
    <div class="footer footer-boxed text-muted">
        © 2017 pr0b.com
    </div>
    <!-- /footer -->

    <script>
        var socket = io();

        // Chat
        var chatText = document.getElementById("chat-text");
        var chatInput = document.getElementById("chat-input");
        var chatForm = document.getElementById("chat-form");

        $('.showChat').click(function()
        {
            if ($('#chatModal').css('display') == 'none'){
                $('#chatModal').show();
                $('#chatModal').draggable();
            }
            else
            {
                $('#chatModal').hide();
            }   
        });

        // Game
        var Img = {};
        Img.player = new Image();
        Img.player.src = '/images/avtest.png';
        Img.map = new Image();
        Img.map.src = '/images/room.png';

        var ctx = document.getElementById("ctx").getContext("2d");
        ctx.canvas.width  = 1156;
        ctx.canvas.height = 650;

        var Player = function(initPack){
            var self = {};
            self.id = initPack.id;
            self.number = initPack.number;
            self.x = initPack.x;
            self.y = initPack.y;
            self.username = initPack.username;

            self.draw = function()
            {
                var width = Img.player.width / 1.5;
                var height = Img.player.height / 1.5;

                ctx.drawImage(Img.player, 0, 0, Img.player.width, Img.player.height, self.x, self.y, width, height)
            }

            Player.list[self.id] = self;

            return self;
        }
        Player.list = {};


        var selfId = null;

        socket.on('init', function(data){
            if(data.selfId){
                selfId = data.selfId;
            }
            for(var i = 0; i < data.player.length; i++){
                new Player(data.player[i]);
            }
        });

        socket.on('update', function(data){
            for(var i = 0; i < data.player.length; i++){
                var pack = data.player[i];
                var p = Player.list[pack.id];
                if(p){
                    if(pack.x !== undefined){
                        p.x = pack.x;
                    }
                    if(pack.y !== undefined){
                        p.y = pack.y;
                    }
                }
            }
        });

        socket.on('remove', function(data){
            for(var i = 0; i < data.player.length; i++){
                delete Player.list[data.player[i]];
            }
        });

        setInterval(function(){
            if(!selfId){
                return;
            }else{
                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                drawMap();
                for(var i in Player.list){
                    Player.list[i].draw();
                }
            }
            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            drawMap();
            for(var i in Player.list){
                Player.list[i].draw();
            }
        }, 10);

        var drawMap = function(){
            ctx.drawImage(Img.map, 0, 0, ctx.canvas.width, ctx.canvas.height);
        }

        socket.on('addToChat', function(data)
        {
            chatText.innerHTML += '<div>' + data + '</div>';
        });

        chatForm.onsubmit = function(e){
            e.preventDefault();
            socket.emit('sendMsgToServer', chatInput.value);
            chatInput.value = '';
        }

        document.onkeydown = function(event)
        {
            if(event.keyCode === 68)
            {
                socket.emit('keyPress', {inputId: 'right', state: true});
            }
            else if(event.keyCode === 83)
            {
                socket.emit('keyPress', {inputId: 'down', state: true});
            }
            else if(event.keyCode === 65)
            {
                socket.emit('keyPress', {inputId: 'left', state: true});
            }
            else if(event.keyCode === 87)
            {
                socket.emit('keyPress', {inputId: 'up', state: true});
            }
        }

        document.onkeyup = function(event)
        {
            if(event.keyCode === 68)
            {
                socket.emit('keyPress', {inputId: 'right', state: false});
            }
            else if(event.keyCode === 83)
            {
                socket.emit('keyPress', {inputId: 'down', state: false});
            }
            else if(event.keyCode === 65)
            {
                socket.emit('keyPress', {inputId: 'left', state: false});
            }
            else if(event.keyCode === 87)
            {
                socket.emit('keyPress', {inputId: 'up', state: false});
            }
        }

        document.oncontextmenu = function(){
            event.preventDefault();
        }
    </script>
</body>

My current app.js file code:

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local'), Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/zworld');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');
var zworld = require('./routes/zworld');

// Init App
var app = express();

// Socket stuff

var serv = require('http').Server(app);

var SOCKET_LIST = [];

var Entity = function(param){
    var self = {
        x: 100,
        y: 100,
        spdX: 0,
        spdY: 0,
        id: ""
    };

    if(param){
        if(param.x){
            self.x = param.x;
        }
        if(param.y){
            self.y = param.y;
        }
        if(param.id){
            self.id = param.id;
        }
    }

    self.update = function(){
        self.updatePosition();
    };

    self.updatePosition = function(){
        self.x += self.spdX;
        self.y += self.spdY;
    };

    return self;
};

var Player = function(param){
        var self = Entity(param);
        self.number = "" + Math.floor(10 * Math.random());
        self.pressingRight = false;
        self.pressingLeft = false;
        self.pressingUp = false;
        self.pressingDown = false;
        self.maxSpd = 5;
        self.username = param.username;

        var super_update = self.update;
        self.update = function(){
            self.updateSpd();
            super_update();
        };

        self.updateSpd = function()
        {
            if(self.pressingRight)
            {
                self.spdX = self.maxSpd;
            }
            else if(self.pressingLeft)
            {
                self.spdX = -self.maxSpd;
            }
            else
            {
                self.spdX = 0;
            }

            if(self.pressingUp)
            {
                self.spdY = -self.maxSpd;
            }
            else if(self.pressingDown)
            {
                self.spdY = self.maxSpd;
            }
            else
            {
                self.spdY = 0;
            }
        };

        self.getInitPack = function(){
            return {
                id:self.id,
                x:self.x,
                y:self.y,
                number:self.number
            };
        };

        self.getUpdatePack = function(){
            return {
                id:self.id,
                x:self.x,
                y:self.y,
                number:self.number
            };
        };

        Player.list[self.id] = self;

        initPack.player.push(self.getInitPack());

        return self;
};

Player.list = {};
Player.onConnect = function(socket){
    var player = Player({
        id: socket.id,
        username: socket.id
    });

    socket.on('keyPress', function(data){
        if(data.inputId === 'left')
        {
            player.pressingLeft = data.state;
        }
        else if(data.inputId === 'right')
        {
            player.pressingRight = data.state;
        }
        else if(data.inputId === 'up')
        {
            player.pressingUp = data.state;
        }
        else if(data.inputId === 'down')
        {
            player.pressingDown = data.state;
        }
    });

    var players = [];

    for(var i in Player.list){
        if(i){
            players.push(Player.list[i].getInitPack());
        }
    }

    socket.emit('init', {
        selfId: socket.id,
        player: Player.getAllInitPack()
    });
};

Player.getAllInitPack = function(){
    var players = [];

    for(var i in Player.list){
        if(i){
            players.push(Player.list[i].getInitPack());
        }
    }

    return players;
};

Player.onDisconnect = function(socket){
    delete Player.list[socket.id];
    removePack.player.push(socket.id);
};

Player.update = function(){
    var pack = [];

    for(var i in Player.list){
        if(i){
            var player = Player.list[i];
            player.update();

            pack.push(player.getUpdatePack());
        }
    }

    return pack;
};

var io = require('socket.io')(serv, {});
io.sockets.on('connection', function(socket){
    socket.id = Math.random();
    SOCKET_LIST[socket.id] = socket;

    Player.onConnect(socket);

    socket.on('disconnect', function(){
        delete SOCKET_LIST[socket.id];
        Player.onDisconnect(socket);
    });

    socket.on('sendMsgToServer', function(data){
        var playerName = ("" + socket.username).slice(2,7);
        for(var i in SOCKET_LIST)
        {
            if(i){
                SOCKET_LIST[i].emit('addToChat', playerName + ': ' + data);
            }
        }
    });

});

var initPack = {player:[]};
var removePack = {player:[]};

setInterval(function(){
    var pack = {
        player:Player.update()
    };

    for(var i in SOCKET_LIST){
        if(i){
            var socket = SOCKET_LIST[i];
            socket.emit('init', initPack);
            socket.emit('update', pack);
            socket.emit('remove', removePack);
        }
    }
    initPack.player = [];
    removePack.player = [];
}, 1000/60);

// Socket stuff end

// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');

// BodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

// Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Express Session
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

// Passport Init
app.use(passport.initialize());
app.use(passport.session());

// Express Validator
app.use(expressValidator({
    errorFormatter: function(param, msg, value){
        var namespace = param.split('.'),
        root = namespace.shift(),
        formParam = root;

        while(namespace.length){
            formParam += '[' + namespace.shift() + ']';
        }

        return{
            param : formParam,
            msg : msg,
            value : value
        };
    }
}));

// Connect Flash
app.use(flash());

// Global Vars
app.use(function (req, res, next){
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
});

app.use('/', routes);
app.use('/users', users);
app.use('/zworld', zworld);

// Set Port
app.set('port', (process.env.PORT || 3000));

serv.listen(app.get('port'), function(){
    console.log('Server started on port ' + app.get('port'));
});



via jsQuestion

No comments:

Post a Comment