Home > php教程 > PHP开发 > Using swoole to extend php websocket example

Using swoole to extend php websocket example

高洛峰
Release: 2016-12-23 18:00:49
Original
1791 people have browsed it

<?php
define(&#39;DEBUG&#39;, &#39;on&#39;);
define("WEBPATH", str_replace("\\","/", __DIR__));
require __DIR__ . &#39;/../libs/lib_config.php&#39;;
class WebSocket extends Swoole\Network\Protocol\WebSocket
{
    /**
     * 下线时,通知所有人
     */
    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.&#39; = &#39;.$ws[&#39;message&#39;]);
        $this->send($client_id, "Server: ".$ws[&#39;message&#39;]);
  //$this->broadcast($client_id, $ws[&#39;message&#39;]);
    }
    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 \Swoole\Log\EchoLog(true)); //Logger
$server = new \Swoole\Network\Server(&#39;0.0.0.0&#39;, 9503);
$server->setProtocol($AppSvr);
//$server->daemonize(); //作为守护进程
$server->run(array(&#39;worker_num&#39; =>4));
Copy after login


更多使用swoole扩展php websocket示例相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template