PHP Socket.IO有时仅连接

时间:2018-08-23 14:40:06

标签: php sockets websocket

我有一个很大的问题,那就是我正在尝试从客户端使用Socket.IO连接到套接字,有时会连接,有时却没有。

这种情况真的很烦人。这是我的代码

客户端

window.db.connection = io(db_vars.SOCKET.URL + ":" + db_vars.SOCKET.PORT);

window.db.connection.emit('add user', this.username, function(response) {
     console.log(response);
});

window.dibibot.connection.on('login', function(data) {
     console.log(data);
});

服务器端

$io->on('connection', function($socket)
        {
            $socket->loggedUser = false;

            // cuando se ejecute en el cliente el evento add user

            $socket->on('add user', function ($username, $callback) use($socket)
            {
                global $usernames, $numUsers;
                // guardamos al usuario en sesión
                $socket->username = json_decode($username, true);
                $socket->username["SOCKET_ID"] = $socket->id;

                //añadimos al cliente a la lista global
                $usernames[$socket->username["WP_USER_DATA"]['guid']] = $socket->username;
                ++$numUsers;

                $socket->loggedUser = true;

                $socket->emit('login', array( 
                    'numUsers' => $numUsers,
                    'usernames' => $usernames
                ));

                call_user_func($callback, "ok");

                foreach ($usernames as $key => $value) {
                    if($value["DIBIBOT_USER_ROLE"] == "dibibot_operator") {
                        $socket->to($value["SOCKET_ID"])->emit('user joined', array(
                            'username' => $socket->username,
                            'numUsers' => $numUsers,
                            "usernames"=> $usernames
                        ));
                    }
                } 
            });
        });

正如我所说,可能会发生什么,有时它会连接而有时却不执行,并且我不知道会发生什么,也许是一些socket.IO配置?

0 个答案:

没有答案