```php
class Websocket
{
public $server;
/**
* @var Redis
*/
public $_reids;
// 设置运行时参数
protected $options = [
'worker_num' => 3, //worker进程数,一般设置为CPU数的1-4倍
'daemonize' => true, //启用守护进程
'log_file' => './swoole.log', //指定swoole错误日志文件
'log_level' => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
// 'dispatch_mode' => 1, //数据包分发策略,1-轮询模式
'enable_coroutine' => true, //自动生成携程
];
public function __construct()
{
$this->server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$this->server->set($this->options);
$this->server->on('ManagerStart',array($this,'onManagerStart'));
$this->server->on('WorkerStart',array($this,'onWorkerStart'));
$this->server->on('open',array($this,'onOpen'));
$this->server->on('message', array($this,'onMessage'));
$this->server->on('close', [$this,'onClose']);
$this->server->on('WorkerStop', [$this,'onWorkerStop']);
$this->server->on('WorkerExit', [$this,'onWorkerExit']);
$this->server->on('ManagerStop', [$this,'onManagerStop']);
$this->server->start();
}
/**
* Notes:
* DESC:这里的管理跟workerstart引入的是两个区域的概念
* Date: 2020/3/26 15:01
* @param \Swoole\Server $server
*/
public function onManagerStart(Swoole\Server $server){
if (class_exists('Loader')) {
require 'Loader.php';
spl_autoload_register('Loader::autoload');
}
echo "服务器onManagerStart开启工作\n";
}
public function onWorkerStart(Swoole\Server $server, int $workerId){
require 'Loader.php';
spl_autoload_register('Loader::autoload');
echo "work:{$workerId}开启工作\n";
}
public function onOpen(Swoole\WebSocket\Server $server, $request) {
Business::connect($server, $request);
}
function onMessage(Swoole\WebSocket\Server $server, $frame) {
echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
if($frame->data == '重启'){
echo '正在重启\n';
$server->reload();
$server->push($frame->fd, "server: {$frame->data}123");
}
Business::business($frame,$server);
}
function onClose($ser, $fd) {
echo "client {$fd} closed\n";
Business::close($ser, $fd);
}
function onWorkerStop(Swoole\WebSocket\Server $server, int $workerId) {
echo "work:{$workerId}服务端强制关闭退出\n";
}
function onWorkerExit(Swoole\WebSocket\Server $server, int $workerId) {
echo "服务端{$workerId}关闭退出\n";
}
/**
* Notes:服务停止 最后的回调
* Date: 2020/3/26 14:41
* @param Server $serv
*/
function onManagerStop(Swoole\WebSocket\Server $serv){
echo "服务端onManagerStop\n";
// Business::clearFlush();
}
}
new Websocket();
```
日志里没有报错 ,就无缘无故的 ws服务就关闭了