配置参数例子
测试的代码主要功能:开启一个tcp服务器。然后设置了管理进程和工作进程start的回调进行更名。设置了pid_file保存了服务端启动的mast进程。
<?php
//创建Server对象,监听 127.0.0.1:9501端口
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array(
'max_request ' => 10, //reactor thread num
'worker_num' => 4, //worker process num
'log_file' => 'swoole.log',
'pid_file' => 'server.pid',
));
$serv->on('managerStart',function($serv){
swoole_set_process_name("managerprocess");
});
$serv->on('workerStart',function($serv, $worker_id){
if($worker_id >= $serv->setting['worker_num']) {
swoole_set_process_name("workprocess_".($worker_id-$serv->setting['worker_num']));
} else {
swoole_set_process_name("workprocess_{$worker_id}");
}
});
$serv->on('start',function($serv){
echo "到这一步说明服务已经起来了,manager,work都已经回调start完成";
});
//监听连接进入事件
$serv->on('connect', function ($serv, $fd) {
echo "Client: Connect.\n";
});
//监听数据接收事件
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, "Server: ".$data);
});
//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
//启动服务器
$serv->start();
?>
下面写一个脚本去重启和停止服务端。(原理就是给mast进程发送信号)
<?php
$options = 's';
$command = getopt($options);
$pidFile = 'server.pid';
if(isset($command['s'])){
if($command['s']=='stop'){
stop();
}else{
reload();
}
}else{
die("请输入-s stop|reload");
}
function stop(){
global $pidFile;
if (file_exists($pidFile)) {
$pid = file_get_contents($pidFile);
if (!swoole_process::kill($pid, 0)) {
echo "PID :{$pid} not exist \n";
return false;
}
swoole_process::kill($pid);
//等待5秒
$time = time();
$flag = false;
while (true) {
usleep(1000);
if (!swoole_process::kill($pid, 0)) {
echo "server stop at " . date("y-m-d h:i:s") . "\n";
if (is_file($pidFile)) {
unlink($pidFile);
}
$flag = true;
break;
} else {
if (time() - $time > 5) {
echo "stop server fail.try again \n";
break;
}
}
}
return $flag;
} else {
echo "pid 文件不存在,请执行查找主进程pid,kill!\n";
return false;
}
}
function reload(){
global $pidFile;
if (file_exists($pidFile)) {
$sig = SIGUSR1;
$pid = file_get_contents($pidFile);
if (!swoole_process::kill($pid, 0)) {
echo "pid :{$pid} not exist \n";
return;
}
swoole_process::kill($pid, $sig);
echo "send server reload command at " . date("y-m-d h:i:s") . "\n";
} else {
echo "pid 文件不存在,请执行查找主进程pid,kill!\n";
}
}
?>