首页 > 解决方案 > Php Ratchet — 如何跟踪连接中断?

问题描述

如何在 Ratchet 中跟踪连接中断 - 我使用主页中的示例。但是当客户端断开连接时(也就是说,它并没有关闭它,而是例如当网络掉线和连接丢失时),onClose 或 onError 方法不会被调用......我如何跟踪这样的连接 -我想在它坏的时候做一些动作。

例子

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

    // Make sure composer dependencies have been installed
    require __DIR__ . '/vendor/autoload.php';

/**
 * chat.php
 * Send any incoming messages to all connected clients (except sender)
 */
class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        $conn->close();
    }
}

    // Run the server application through the WebSocket protocol on port 8080
    $app = new Ratchet\App('localhost', 8080);
    $app->route('/chat', new MyChat, array('*'));
    $app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
    $app->run();

如果客户端关闭了网络接口,连接会中断,但不会调用 onClose 或 onError 方法。如何检测和处理连接中断?

标签: phpratchet

解决方案


推荐阅读