php - 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
);
解决方案
推荐阅读
- django - Caddy 服务器:使用 docker-compose 在反向代理后面运行 Django 应用程序
- python - Discord.py 在 vc 中获取用户分钟数
- css - 居中带有动态内容的传单 divIcon 标记
- mysql - MySql Table 占用大量空间
- nested - 扫描 ABAP 报告以查找将方法调用展开到级别 N 的字符串?
- python - Python html模块:返回子节点内所有出现的标记
- java - 如果不存在如何更新mongo db中的字段,如果存在则更新其他字段
- javascript - 如何将json值记录到控制台?
- android - SurfaceView 显示黑屏 - Android Studio
- java - 查找不重复的数字