0
votes

Probably it's a stupid error but i dont know how to solve it. This is my server side code.

// Dependencies
var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');

var app = express();
var server = http.Server(app);
var io = socketIO(server);

app.set('port', 4040);
app.use('/client', express.static(__dirname + '/client'));

app.get('/', function(request, response) {
    response.sendFile(path.join(__dirname, '/client/index.html'));
});

// Starts the server.
server.listen(4040, function() {
    console.log('Starting server on port 4040');
});

// Add the WebSocket handlers
var SOCKET_LIST = {};
var playerNumber = 0;
var started = false;

io.on('connection', function(socket) {
    socket.id = Math.random();
    SOCKET_LIST[socket.id] = socket;

    console.log(socket.id);
    console.log(SOCKET_LIST);
    console.log(Object.keys(SOCKET_LIST));

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

When i activate server with node and a client connects it correctly print the three console.log() containing: socket.id, SOCKET_LIST and list of keys in SOCKET_LIST with the key corrisponding to socket.id.

The problem is that on disconnect i receive the error:

delete SOCKET_LIST[socket.id]; ^

TypeError: Cannot read property 'id' of undefined at Socket. (C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\app.js:82:31) at Socket.emit (events.js:315:20) at Socket.emit >C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\node_modules\socket.io\lib\socket.js:142:10) at Socket.onclose (C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\node_modules\socket.io\lib\socket.js:454:8) at Client.onclose (C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\node_modules\socket.io\lib\client.js:254:24) at Socket.emit (events.js:327:22) at Socket.onClose (C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\node_modules\engine.io\lib\socket.js:318:10)> at Object.onceWrapper (events.js:421:28) at WebSocket.emit (events.js:315:20) at WebSocket.Transport.onClose (C:\Users\utente\Desktop\SistemiOrientatiAdInternet\Progetto\node_modules\engine.io\lib\transport.js:127:8)

Any suggestions?

1

1 Answers

0
votes

The reason is once your socket has disconnected, it no longer exists and you can't access its id anymore. You can try saving the id in a variable so you can remove it from your dictionary later.

socket.id = Math.random();
let socketId = socket.id
SOCKET_LIST[socketId] = socket;

...

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