如何在Web套接字连接中接收消息?

时间:2019-12-04 13:12:33

标签: php api websocket ratchet

对于我的项目,有必要在客户端(应用程序用户)和服务器之间建立连接。因此,我想使用WebSocket Ratchet保持连接,以便双方都可以发出请求。我使用php来做到这一点。问题是已创建端口,但我无法接收消息。因此,不会执行onMessage函数。在一个终端中,我执行创建套接字的php文件。在另一个终端中,我对端口执行ping操作,但该端口可正常工作,但未打印添加的消息。因此,要么没有收到消息,要么没有执行该功能。

此图显示了如何建立与WebSocket的连接:

That's how I try to open a Web Socket Connection and sending messages via telnet

以下代码创建了套接字,并且应该接收并打印消息:

<?php
ini_set('display_errors',1);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once '/var/www/vendor/autoload.php';
class Chat 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();
    }
}



    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        8081
    );

    $server->run();
?>

谢谢!

0 个答案:

没有答案