Mil*_*vić 1 php websocket ratchet
(注意:我故意websocket在这里放置了不充分的标签,因为这是 WebSocket 专家了解 Ratchet 架构的最佳机会)。
我准备实现 HTML5 服务器端事件,我需要的是服务器端解决方案。由于挂起 Apache 的每个连接一个进程(连接池限制、内存消耗...)是出于考虑,我希望Ratchet 项目能够有所帮助,因为它是维护最多的项目,并且它们拥有http与其他组件耦合的服务器。
我的问题是:我该如何使用它?不是用于升级http请求(默认用法),而是用于提供动态生成的内容。
到目前为止我尝试过什么?
Ratchet按照教程中的说明安装
测试过的 WebSocket 功能 - 工作正常
遵循描述http服务器组件的页面上给出的非常基本的指令集:
/bin/http-server.php
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
require dirname(__DIR__) . '/vendor/autoload.php';
$http = new HttpServer(new MyWebPage);
$server = IoServer::factory($http);
$server->run();
Run Code Online (Sandbox Code Playgroud)
专家不应该知道MyWebPage这里需要声明类才能使服务器工作,但是如何声明呢?
Ratchet 文档似乎没有涵盖这一点。
您的MyWebPage班级需要实施HttpServerInterface. 由于这只是一个简单的请求/响应,因此您需要发送响应,然后在onOpen()类的方法中关闭连接:
<?php
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Ratchet\ConnectionInterface;
use Ratchet\Http\HttpServerInterface;
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我最终使用了该类Ratchet\App,而不是Ratchet\Http\HttpServer因为它允许您在其他事情中设置路由,所以您/bin/http-server.php将如下所示:
<?php
use Ratchet\App;
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new App('localhost', 8080, '127.0.0.1');
$app->route('/', new MyWebPage(), ['*']);
$app->run();
Run Code Online (Sandbox Code Playgroud)
当您运行php bin/http-server.php并访问http://localhost:8080时,您应该看到 Hello World! 浏览器中的响应。
这就是基本请求/响应系统所需的全部内容,但它可以通过实现 HTML 模板和类似的东西来进一步扩展。我自己在一个小测试项目中实现了这一点,我已将其与许多其他东西一起上传到 github,包括一个可以扩展到不同页面的抽象控制器。
| 归档时间: |
|
| 查看次数: |
1811 次 |
| 最近记录: |