首页 > 解决方案 > Ratchet PHP WebSocket:连接后立即断开连接

问题描述

我正在尝试向我的 WebSocket 代码添加一个定期计时器。

<?php

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\BetSocket;

require dirname( __FILE__ ) . '/vendor/autoload.php';

$dbConn = new MysqliDb("localhost", "root", "", "betball_game");

if( ! $dbConn ){
   echo 'Database Connection Failed.'; die;
}

$loop = React\EventLoop\Factory::create();
$socket = new \React\Socket\Server('127.0.0.1:8080', $loop);
$server = new \Ratchet\Server\IoServer(
    new BetSocket($dbConn, $loop), $socket, $loop
);
echo "Server::Running \n";
$server->run();

// $server = IoServer::factory(
//     new HttpServer(
//         new WsServer(
//             new BetSocket($dbConn)
//         )
//     ),
//     8080
// );
// echo "Server::Running \n";
// $server->run();

和 BetSocket 类代码:

class BetSocket implements MessageComponentInterface {

    protected $db;
    protected $bet_state = "BET_IDLE";

    public function __construct($mysqli_conn, $loop)
    {
       $this->db = $mysqli_conn;
       $this->clients = new \SplObjectStorage;
       $this->players = new \SplObjectStorage;
       $loop->addPeriodicTimer(5, function (\React\EventLoop\Timer\Timer $timer) {
            echo "testing \n";
        });
    }

public function onOpen(ConnectionInterface $conn) {

    echo "\n onOpen \n";

    // Store the new connection in $this->clients
    $this->clients->attach($conn);

    echo "New connection: ({$conn->resourceId})\n";
    echo "No of clients: ({$this->clients->count()}) \n";
}

public function onClose(ConnectionInterface $conn) {
        echo "\n onClose ({$conn->resourceId}) \n";
        $this->clients->detach($conn);
}

当我尝试从我的 javascript 客户端连接到此 WebSocket 时:socket = new WebSocket('ws://127.0.0.1:8080');

 onOpen
New connection: (42)
No of clients: (1)
onClose (42)
testing
testing

但是计时器正在运行...

我正在本地机器上测试这个应用程序。客户端应用程序正在 XAMPP 服务器上运行。

如果我评论定期计时器代码...然后能够连接到 WebSocket。

没有计时器的现有代码工作正常......

 $server = IoServer::factory(
     new HttpServer(
         new WsServer(
             new BetSocket($dbConn)
         )
     ),
     8080
 );

标签: phpwebsockettimerratchet

解决方案


推荐阅读