[英]How to use Ratchet to respond to HTML5 server-side events?
(注意:我故意在此處放置了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();
不應該是專家來弄清楚這里的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();
}
}
我最終使用了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();
當您運行php bin/http-server.php
並訪問http:// localhost:8080時,您應該看到Hello World! 瀏覽器中的響應。
這是基本請求/響應系統所需的全部,但是可以通過實現HTML模板等來進一步擴展它。 我已經在一個小的測試項目中自己實現了這一點,我將它與許多其他內容一起上傳到了github,包括一個抽象控制器,可以將其擴展到不同的頁面。
檢查上面的鏈接。 這里的人正在使用Ratchet構建實時聊天服務器。 他基本上是先存儲usernames
,然后再發送/廣播給所有人。 您可以對其進行修改,並在發送特定的username
或uid
時進行檢查,然后僅將數據發送給他們。 您可以動態生成數據並發送給特定用戶或所有人。 可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.