建站教学网,让你建站更便捷和轻松!
您当前的位置:首页 > 网络编程 > PHP教程

使用swoole扩展php websocket示例

来源:建站教学网  时间:2019-10-09 10:50:19

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

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.' = '.$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 /Swoole/Log/EchoLog(true)); //Logger

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

责任编辑:自由哥

免责声明:建站教学网内容来源于本网和互联网,如媒体、公司、企业或个人对该部分主张知识产权,请与本站联系,本网站将迅速采取适当措施,否则,与之有关的知识产权纠纷本网站不承担任何责任。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
CopyRight 2008-2019, JZREAD.COM, Inc. All Rights Reserved
皖ICP备07015033号