未定义Socket.io ReferenceError客户端

时间:2014-03-20 14:28:52

标签: javascript node.js socket.io client referenceerror

我正在尝试使用顶部答案how to get session id of socket.io client in Client中描述的方法找到连接到我的socket.io/node.js服务器的客户端的ID,但是当我这样做时,我收到错误消息

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)

我的代码如下

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")
    });
});

有谁知道如何解决这个问题?我只能假设我没有要求()我应该拥有的东西,但我不知道是什么。

1 个答案:

答案 0 :(得分:0)

你没有变量client。请改用socket

更改行

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

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

顺便说一句,我认为你应该在这里使用playerlist.length