当前位置:首页 > PHP教程 > php应用 > 列表

使用swoole扩展php websocket示例

发布:smiling 来源: PHP粉丝网  添加日期:2020-09-09 15:41:38 浏览: 评论:0 

WebSocket规范的目标是在浏览器中实现和服务器端双向通信。双向通信可以拓展浏览器上的应用类型,如果你想要用PHP来写websocket应用,那swoole_framework一定是最好的选择,需要的朋友可以参考下,代码如下:

  1. <?php 
  2. define('DEBUG', 'on'); 
  3. define("WEBPATH", str_replace("\\","/", __DIR__)); 
  4. require __DIR__ . '/../libs/lib_config.php'; 
  5.  
  6. class WebSocket extends Swoole\Network\Protocol\WebSocket 
  7. { 
  8.     /** 
  9.      * 下线时,通知所有人 
  10.      */ 
  11.     function onClose($serv, $client_id, $from_id) 
  12.     { 
  13.         //将下线消息发送给所有人 
  14.         //$this->log("onOffline: " . $client_id); 
  15.         //$this->broadcast($client_id, "onOffline: " . $client_id); 
  16.         parent::onClose($serv, $client_id, $from_id); 
  17.     } 
  18.  
  19.     /** 
  20.      * 接收到消息时 
  21.      * @see WSProtocol::onMessage() 
  22.      */ 
  23.     function onMessage($client_id, $ws) 
  24.     { 
  25.         $this->log("onMessage: ".$client_id.' = '.$ws['message']); 
  26.         $this->send($client_id, "Server: ".$ws['message']); 
  27.   //$this->broadcast($client_id, $ws['message']); 
  28.     } 
  29.  
  30.     function broadcast($client_id, $msg) 
  31.     { 
  32.         foreach ($this->connections as $clid => $info) 
  33.         { 
  34.             if ($client_id != $clid) 
  35.             { 
  36.                 $this->send($clid, $msg); 
  37.             } 
  38.         } 
  39.     } 
  40. } 
  41.  
  42. //phpfensi.com 
  43. $AppSvr = new WebSocket(); 
  44. $AppSvr->loadSetting(__DIR__."/swoole.ini"); //加载配置文件 
  45. $AppSvr->setLogger(new \Swoole\Log\EchoLog(true)); //Logger 
  46.  
  47. $server = new \Swoole\Network\Server('0.0.0.0', 9503); 
  48. $server->setProtocol($AppSvr); 
  49. //$server->daemonize(); //作为守护进程 
  50. $server->run(array('worker_num' =>4)); 

Tags: swoole websocket

分享到: