如何使用Ratchet来响应HTML5服务器端事件



(注意:我有意在这里放置了不充分的websocket标记,因为这是WebSocket专家了解Ratchet架构的最佳机会)。

我准备实现HTML5服务器端事件,我需要的是服务器端解决方案。由于不考虑挂起Apache的每个连接一个进程(连接池限制、内存消耗…),我希望Ratchet项目能有所帮助,因为它是维护最多的项目,而且他们有http服务器和其他组件。

我的问题是:我该如何使用它?不是用于升级http请求(默认用法),而是用于提供动态生成的内容。

到目前为止我尝试了什么

  1. 已安装Ratchet,如教程中所述

  2. 经过测试的WebSocket功能-正常工作

  3. 遵循页面上给出的描述http服务器组件的一组非常基本的指令:

/bin/http-server.php

use RatchetHttpHttpServer;
use RatchetServerIoServer;
    require dirname(__DIR__) . '/vendor/autoload.php';
    $http = new HttpServer(new MyWebPage);
$server = IoServer::factory($http);
$server->run();

不应该是一个专家来弄清楚这里的MyWebPage类需要声明才能让服务器工作,但如何声明呢?

棘轮文件似乎没有涵盖这一点。

您的MyWebPage类需要实现HttpServerInterface。由于这只是一个简单的请求/响应,您需要发送一个响应,然后在类的onOpen()方法中关闭连接:

<?php
use GuzzleHttpMessageRequestInterface;
use GuzzleHttpMessageResponse;
use RatchetConnectionInterface;
use RatchetHttpHttpServerInterface;
class MyWebPage implements HttpServerInterface
{
    protected $response;
    public function onOpen(ConnectionInterface $conn, RequestInterface $request = null)
    {
        $this->response = new Response(200, [
            'Content-Type' => 'text/html; charset=utf-8',
        ]);
        $this->response->setBody('Hello World!');
        $this->close($conn);
    }
    public function onClose(ConnectionInterface $conn)
    {
    }
    public function onError(ConnectionInterface $conn, Exception $e)
    {
    }
    public function onMessage(ConnectionInterface $from, $msg)
    {
    }
    protected function close(ConnectionInterface $conn)
    {
        $conn->send($this->response);
        $conn->close();
    }
}

我最终使用了RatchetApp类而不是RatchetHttpHttpServer,因为它允许您设置路由和其他东西,所以您的/bin/http-server.php看起来像这样:

<?php
use RatchetApp;
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new App('localhost', 8080, '127.0.0.1');
$app->route('/', new MyWebPage(), ['*']);
$app->run();

当您运行php bin/http-server.php并访问http://localhost:8080你应该看看Hello World!响应。

这就是基本的请求/响应系统所需要的全部内容,但它可以通过实现HTML模板和类似的东西来进一步扩展。我自己在一个小测试项目中实现了这一点,我已经上传到github,还有很多其他东西,包括一个抽象控制器,我可以扩展到不同的页面。

使用Ratchet的聊天服务器-基本

聊天服务器使用棘轮-高级

检查上面的链接。这里的家伙正在使用Ratchet构建一个实时聊天服务器。他最初基本上存储CCD_ 15,然后向所有人发送/广播。您可以修改它,并在发送时检查某个usernameuid当前处于活动状态,并仅向它们发送数据。您可以动态生成数据并发送给特定用户或所有用户。也许这会有所帮助。

最新更新