【问题标题】:RatchetPHP - Client gets disconnected from server right before receiving a message from the serverRatchetPHP - 客户端在收到来自服务器的消息之前立即与服务器断开连接
【发布时间】:2019-11-09 16:43:11
【问题描述】:

所以,我正在尝试 Ratchet 教程 (http://socketo.me/docs/hello-world),但我遇到了一个问题: 每次在 ConnectionInterface 对象上调用 send() 方法时,此客户端都会与服务器断开连接。

下面的例子:

SSH 终端

php server1.php
New connection! (54)
New connection! (83)
Connection 83 sending message "test msg" to 1 other connection
Connection 54 has disconnected

我什至没有在客户端 54 上收到“测试信息”。

我的文件:

server1.php

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat1;

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

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

    $server->run();

Chat1.php

?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat1 implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

【问题讨论】:

    标签: php websocket composer-php ratchet reactphp


    【解决方案1】:

    我遇到了类似的错误。

    当我检查错误时,我注意到在客户端,当我收到消息时,我在接收方法中编写了会导致连接与客户端断开连接的内容.

    此错误与服务器无关

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2010-10-17
      • 2013-03-28
      • 2012-03-21
      • 2013-03-28
      相关资源
      最近更新 更多