加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用swoole扩展php websocket示例

发布时间:2020-12-12 20:03:19 所属栏目:PHP教程 来源:网络整理
导读:代码如下: define('DEBUG','on'); define("WEBPATH",str_replace("","/",__DIR__)); require __DIR__ . '/../libs/lib_config.php'; class WebSocket extends SwooleNetworkProtocolWebSocket { /** * 下线时,通知所有人 */ function onClose($serv,$c

代码如下:
define('DEBUG','on');
define("WEBPATH",str_replace("","/",__DIR__));
require __DIR__ . '/../libs/lib_config.php';

class WebSocket extends SwooleNetworkProtocolWebSocket
{
/**
* 下线时,通知所有人
*/
function onClose($serv,$client_id,$from_id)
{
//将下线消息发送给所有人
//$this->log("onOffline: " . $client_id);
//$this->broadcast($client_id,"onOffline: " . $client_id);
parent::onClose($serv,$from_id);
}

/**
* 接收到消息时
* @see WSProtocol::onMessage()
*/
function onMessage($client_id,$ws)
{
$this->log("onMessage: ".$client_id.' = '.$ws['message']);
$this->send($client_id,"Server: ".$ws['message']);
//$this->broadcast($client_id,$ws['message']);
}

function broadcast($client_id,$msg)
{
foreach ($this->connections as $clid => $info)
{
if ($client_id != $clid)
{
$this->send($clid,$msg);
}
}
}
}


$AppSvr = new WebSocket();
$AppSvr->loadSetting(__DIR__."/swoole.ini"); //加载配置文件
$AppSvr->setLogger(new SwooleLogEchoLog(true)); //Logger

$server = new SwooleNetworkServer('0.0.0.0',9503);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array('worker_num' =>4));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读