Page 1 of 1

Socket.io Node.js tutorial

Posted: Wed Jun 10, 2015 8:22 am
by Thaywood
I have used the socket and node.js tutorial but i am having problems with my code it never broadcasts or fulfills disconnect2? The rest works fine but i have included the error part.

app.js

Code: Select all

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8470);

function handler (req, res) {
    fs.readFile(__dirname + '/index.html',
    function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200);
        res.end(data);
    });
}


var playerlist = []

io.sockets.on('connection', function (socket) {
    socket.on('disconnect2', function(room){
        name = socket.clientname;
        for (var i in playerlist) {
            if (name === playerlist[i].name) {
                if (room === playerlist[i].room) {
                    playerlist = playerlist.splice(i, 1);
		    delete playerlist[i];
                }
            }
        }
        io.sockets.emit('netreplayer', playerlist, name);
    });
});
game.js

Code: Select all

var namerand = Math.floor(Math.random()*999);
var playername = "player" + namerand;
var socket = io.connect('http://localhost:8470');

socket.on('netreplayer', function (playerlist, name) {
    playersinroom = []
    for(var i in playerlist) {
        if(playername != playerlist[i]["name"]) {
            if(playerroom === playerlist[i]["room"]) {
                d = playersinroom.length -  1
                playersinroom[d] = playerlist[i];
                playersinroom[d]["lastlocx"] = playersinroom[d]["cellx"] * 32
                playersinroom[d]["lastlocy"] = playersinroom[d]["celly"] * 36
                var grid = new PF.Grid(40, 18);
                playersinroom[d]["path"] = finder.findPath(Math.floor(playersinroom[d]["lastlocx"] / 32), Math.floor(playersinroom[d]["lastlocy"] / 36), playersinroom[d]["cellx"], playersinroom[d]["celly"], grid)
            }
        }
    }
});

window.addEventListener("beforeunload", function(e){
   socket.emit('disconnect2', playerroom);
}, false);

Re: Socket.io Node.js tutorial

Posted: Wed Jun 10, 2015 3:33 pm
by hallsofvallhalla
whats the error you are getting?

Re: Socket.io Node.js tutorial

Posted: Fri Jun 12, 2015 5:39 pm
by Thaywood
None, it doesnt disconnect so the array of players doesnt lose the disconnected players

Re: Socket.io Node.js tutorial

Posted: Thu Aug 06, 2015 12:40 pm
by Chris
That's an annoying feature, sometimes the disconnect event listeners don't work.

Use an interval to check if the client still has a connection. If there is no connection for that user, remove them from the array.