WebSocket 组件

提供 WebSocket 服务端和客户端类。

WebSocket 服务端类

Phalcon\Websocket\Server 可以等待客户端的连接请求以及接收客户端发送的数据。

  1. <?php
  2.  
  3. $server = new Phalcon\Websocket\Server(8080, Phalcon\Websocket\Server::WRITE_TEXT);
  4. $server->on(Phalcon\Websocket\Server::ON_ACCEPT, function($server, $conn){
  5. echo 'Accept'.PHP_EOL;
  6. $conn->send('Hello world!');
  7. });
  8. $server->on(Phalcon\Websocket\Server::ON_CLOSE, function($server){
  9. echo 'Close'.PHP_EOL;
  10. });
  11. $server->on(Phalcon\Websocket\Server::ON_DATA, function($server, $conn, $data){
  12. echo 'Data '.$data.PHP_EOL;
  13. $server->broadcast($data, [$conn->getUid()]);
  14. });
  15. $server->on(Phalcon\Websocket\Server::ON_TICK, function($server){
  16. echo 'Tick'.PHP_EOL;
  17. });
  18. $server->run();

WebSocket 客户端类

Phalcon\Websocket\Client 可以发送数据给服务端以及接收来自服务端的数据。

  1. <?php
  2.  
  3. $client = new Phalcon\Websocket\Client('127.0.0.1', 8080, NULL, Phalcon\Websocket\Server::WRITE_TEXT);
  4. $client->on(Phalcon\Websocket\Client::ON_ACCEPT, function($client, $conn){
  5. echo 'Accept'.PHP_EOL;
  6. $conn->send('Hello Server!');
  7. });
  8. $client->on(Phalcon\Websocket\Client::ON_CLOSE, function(){
  9. echo 'Close'.PHP_EOL;
  10. });
  11. $client->on(Phalcon\Websocket\Client::ON_DATA, function($client, $conn, $data){
  12. echo 'Data '.$data.PHP_EOL;
  13. });
  14. $client->on(Phalcon\Websocket\Client::ON_TICK, function($client){
  15. $data = 'Hello Tick!';
  16. echo $data.PHP_EOL;
  17. });
  18. $client->connect();

原文: http://www.myleftstudio.com/reference/websocket.html