当前位置:首页 > PHP教程 > PHP常见问题

使用swoole扩展php websocket示例

复制代码 代码如下:

<?php
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, $client_id, $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));


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!