Extend the php websocket example with swoole

  • 2020-12-22 17:35:33
  • OfStack


<?php
define('DEBUG', 'on');
define("WEBPATH", str_replace("\\","/", __DIR__));
require __DIR__ . '/../libs/lib_config.php';
class WebSocket extends Swoole\Network\Protocol\WebSocket
{
    /**
     *  Notify everyone when you go offline 
     */
    function onClose($serv, $client_id, $from_id)
    {
        // Send the offline message to everyone 
        //$this->log("onOffline: " . $client_id);
        //$this->broadcast($client_id, "onOffline: " . $client_id);
        parent::onClose($serv, $client_id, $from_id);
    }
    /**
     *  When a message is received 
     * @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"); // Load configuration file 
$AppSvr->setLogger(new \Swoole\Log\EchoLog(true)); //Logger
$server = new \Swoole\Network\Server('0.0.0.0', 9503);
$server->setProtocol($AppSvr);
//$server->daemonize(); // As a daemon 
$server->run(array('worker_num' =>4));


Related articles: