Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 连接到套接字(nodeJs)时传入userId参数_Javascript_Node.js_Socket.io - Fatal编程技术网

Javascript 连接到套接字(nodeJs)时传入userId参数

Javascript 连接到套接字(nodeJs)时传入userId参数,javascript,node.js,socket.io,Javascript,Node.js,Socket.io,因此,我有一个服务器,当用户进入我的网页时,他们将连接到该服务器。我使用node js和socket io,当新玩家加入时,我会给他们一个唯一的ID。我通过下面的代码来实现这一点: Server.prototype.startSockets = function() { this.socket = io.listen(this.server); this.socket.of('game').on('connection', function(user) {

因此,我有一个服务器,当用户进入我的网页时,他们将连接到该服务器。我使用node js和socket io,当新玩家加入时,我会给他们一个唯一的ID。我通过下面的代码来实现这一点:

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));
};
html上的js:

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

server = io.connect('http://localhost:8081/game');
它将为用户提供一个ID,然后将其发送回客户端:

server.on('connected', function(response)
{
    userId = response.userId;
    userName = response.userName;
});
我想做的是用一个特定的id连接某人。因此,当某人连接时,他们的id为560,保存在会话中,我打开一个新页面,读取会话id,然后用该id连接他们


我尝试在执行io.connect('localhost…',560)的客户机上传入一个id,但我无法让它工作。任何帮助都会收到

这看起来服务器上只有一个
This.userId
,因此您将为每个连接的用户分配相同的帮助。为什么?为每个连接的用户创建唯一用户id的代码在哪里?yes userId默认设置为1,但就在用户连接并分配该id之后,您可以看到我将其放入。userId++。因此,下一个用户的id将为2,依此类推。如果每次连接某个给定浏览器时,您都希望该浏览器有一个持久的用户id,那么您必须将某种id放入cookie,或者会话cookie,然后将id存储在会话中,或者将id本身放入cookie中。啊,是的,我只想到php会话,我忘了node js有一个cookie模块。所以在我给他们分配一个用户id之前,我可以运行一个函数来检查cookie中是否保存了一个,如果有,分配他们保存的,如果没有,分配给他们this.userId。谢谢,这是总的想法。