Swoole 封装单例模式,热部署 [ 2.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 "我走了";
}
}
〆、辞旧° 陕西汉中
注册时间:2019-07-18
最后登录:2021-06-08
在线时长:8小时3分
最后登录:2021-06-08
在线时长:8小时3分
- 粉丝0
- 金钱55
- 威望20
- 积分335
共 0 条评论