Question

I am trying to find the id of clients that connect to my socket.io/node.js server using the method described in the top answer here how to get session id of socket.io client in Client but when I do I get the error message

C:\Games\My games\Newserver\Server\server.js:5
        playerlist[playerlist.length+1] = [client.id,username]
                                           ^
ReferenceError: client is not defined
    at SocketNamespace.<anonymous> (C:\Games\My games\Newserver\Server\server.js
:5:37)
    at SocketNamespace.EventEmitter.emit [as $emit] (events.js:117:20)
    at connect (C:\Games\My games\Newserver\Server\node_modules\socket.io\lib\na
mespace.js:292:10)
    at C:\Games\My games\Newserver\Server\node_modules\socket.io\lib\namespace.j
s:308:13
    at SocketNamespace.authorize (C:\Games\My games\Newserver\Server\node_module
s\socket.io\lib\namespace.js:252:5)
    at SocketNamespace.handlePacket (C:\Games\My games\Newserver\Server\node_mod
ules\socket.io\lib\namespace.js:302:14)
    at Manager.handleClient (C:\Games\My games\Newserver\Server\node_modules\soc
ket.io\lib\manager.js:698:32)
    at Manager.handleUpgrade (C:\Games\My games\Newserver\Server\node_modules\so
cket.io\lib\manager.js:618:8)
    at Server.<anonymous> (C:\Games\My games\Newserver\Server\node_modules\socke
t.io\lib\manager.js:123:10)
    at Server.EventEmitter.emit (events.js:106:17)

My code is as follows

var io = require('socket.io').listen(1337); //Tells server to use socket.io and to listen on port 1337
var playerlist= new Array(); //Array to store player usernames & client ids of these players

io.sockets.on("connection", function(socket) {
    playerlist[playerlist.length+1] = [client.id,username] //Writing to array, crashes here at client.id
    socket.on("username", function(data) {

        var str = "[Server] User "
        var str2 = data
        var str3 = " connected."
        var finalstr = str.concat(str2.concat(str3))
        socket.broadcast.send(finalstr)
        socket.send("[Server] Connected")
    });
});

Does anyone know how to fix this? I can only assume I haven't require()d something that I should have but I don't know what.

Was it helpful?

Solution

You've got no variable client. Use socket instead.

Change the line

playerlist[playerlist.length+1] = [client.id,username]

to

playerlist[playerlist.length] = [socket.id,username]

By the way, I think you should use playerlist.length here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top