Monday, 24 April 2017

Connect to node js server with a specific user ID

so i have a server which users will connect to when they go on my webpage. Im using node js and socket io and when a new players joins, i give them a unique ID. I do this by the code below:

js on html:

<script defer type="text/javascript" src="http://localhost:8081/socket.io/socket.io.js"></script>

server = io.connect('http://localhost:8081/game');

It then connects to my server with the code below:

Server.prototype.startSockets = function()
{
    this.socket = io.listen(this.server);

    this.socket.of('game').on('connection', function(user)
        {
            user.userId = this.userId;
            user.userName = this.userName + " " + this.userId;

            this.userId++;

            consoleLog('SERVER', user.userName + ' has connected. ID: ' + user.userId)

            user.emit('response', 
            {
                userId: user.userId,
                userName: user.userName
            });

            user.on('disconnect', function()
                {           
                    this.em.emit('cancelHostGame', user.userId, user.userName);
                    consoleLog('SERVER', user.userName + ' has disconnected. ID: ' + user.userId)
                }
                .bind(this));
        }
        .bind(this));
};

It will give the user an ID and then send it back to the client:

server.on('connected', function(response)
{
    userId = response.userId;
    userName = response.userName;
});

What im trying to do is connect someone with a specific id. So when someone connects, they get an id of 560, save it in a session, i open a new page, read the session id and then connect them with that id.

I tried passing in an id on the client where i do io.connect('localhost...', 560) but i couldnt get that to work. Any help is appriciated



via Slavik Ribz

No comments:

Post a Comment