Ratchet
v0.4.4
用于异步服务 WebSocket 的 PHP 库。通过简单的界面构建您的应用程序,并通过组合不同的组件来重用您的应用程序,而无需更改其任何代码。
我们目前的目标是复兴 Ratchet,使其更新到最新版本,并以此为起点进行更大的更新。我们需要您的帮助来实现这一目标,请参阅票号 #1054 了解帮助方法。
需要 Shell 访问权限,建议使用 root 访问权限。为了避免代理/防火墙阻塞,建议在端口 80 或 443 (SSL) 上请求 WebSocket,这需要 root 访问权限。为此,您可以使用反向代理或两台单独的计算机以及同步网络堆栈。您可以在服务器配置文档中找到更多详细信息。
用户和 API 文档可在 Ratchet 的网站上找到:http://socketo.me
请参阅 https://github.com/cboden/Ratchet-examples,了解一些使用 Ratchet 的开箱即用的工作演示。
需要帮助吗?有问题吗?想要提供反馈吗?在 Google 网上论坛邮件列表中写一条消息。
<?php
use Ratchet MessageComponentInterface ;
use Ratchet ConnectionInterface ;
// Make sure composer dependencies have been installed
require __DIR__ . ' /vendor/autoload.php ' ;
/ * *
* chat . php
* Send any incoming messages to all connected clients ( except sender )
* /
class MyChat implements MessageComponentInterface {
protected $ clients ;
public function __construct () {
$ this -> clients = new SplObjectStorage ;
}
public function onOpen ( ConnectionInterface $ conn ) {
$ this -> clients -> attach ( $ conn );
}
public function onMessage ( ConnectionInterface $ from , $ msg ) {
foreach ( $ this -> clients as $ client ) {
if ( $ from != $ client ) {
$ client -> send ( $ msg );
}
}
}
public function onClose ( ConnectionInterface $ conn ) {
$ this -> clients -> detach ( $ conn );
}
public function onError ( ConnectionInterface $ conn , Exception $ e ) {
$ conn -> close ();
}
}
// Run the server application through the WebSocket protocol on port 8080
$ app = new Ratchet App ( ' localhost ' , 8080 );
$ app -> route ( ' /chat ' , new MyChat , array ( ' * ' ));
$ app -> route ( ' /echo ' , new Ratchet Server EchoServer , array ( ' * ' ));
$ app -> run ();
$ php chat.php
// Then some JavaScript in the browser:
var conn = new WebSocket ( 'ws://localhost:8080/echo' ) ;
conn . onmessage = function ( e ) { console . log ( e . data ) ; } ;
conn . onopen = function ( e ) { conn . send ( 'Hello Me!' ) ; } ;