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!' ) ; } ;