〆、辞旧° 2020-04-06 17:12:57 8357次浏览 0条评论 2 0 0
<?php
/**
 * 单例模式
 */
class SwooleServer{
    private static $instance;
    private static $server;
    private $message;//处理消息的对象

    private function __construct(){
        //>>1.创建websocket对象
        //self::$server = new swoole_websocket_server("0.0.0.0",39999);
        self::$server = new Swoole\WebSocket\Server('0.0.0.0', '39999');
        //>>2.注册事件
        self::$server->on("open",[$this,"onInit"]);
        self::$server->on("message",[$this,"onMessage"]);
        self::$server->on("close",[$this,"onClose"]);
        self::$server->on("workerStart",[$this,"onWorkerStart"]);
    }
    //连接时
    public function onInit($server,$req){

    }
    //发送消息
    public function onMessage($server,$frame){
        self::$server->reload();//从新加载onWorkerStart的类,不需要重启服务
        //$frame->data = "{'cmd':'login','data':'55555'}";
        $data = json_decode($frame->data,true);
        if(method_exists($this->message,$data['cmd'])){
            call_user_func([$this->message,$data['cmd']],$frame->fd,$data);
        }
    }
    //断开连接
    public function onClose($server,$fd){

    }
    public function onWorkerStart(){
        //热部署
        echo "来了老弟!";
        require "./Handler.php";//加载业务处理类
        $this->message = new Handler();
    }
    public static function getInstance(){
        if(!self::$instance instanceof self ){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 创建对象,启动服务器
     */
    public function start(){
        self::$server->start();
    }
    
}
SwooleServer::getInstance()->start();

业务文件

<?php

class Handler{
    /**
     * clinet_id 客户唯一编号
     * data 登录信息
     */
    public function login($clinet_id,$data){
        echo $clinet_id."我来了";
        print_r($data);
    }
    public function logout(){
        echo "我走了";
    }
}
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册