Beispiel #1
0
 public function setTimerInWorker(\swoole_server $serv, $worker_id)
 {
     if ($worker_id == 0) {
         echo "Start: " . microtime(true) . "\n";
         $serv->addtimer(3000);
     }
 }
Beispiel #2
0
 function onWorkerStart(\swoole_server $serv, $worker_id)
 {
     $this->log("worker start {$worker_id}");
     $this->worker_id = $worker_id;
     if ($worker_id == 0) {
         //$serv->addtimer(self::CHECK_TIME*60*1000);
         $serv->addtimer(5000);
         $this->log("{$this->worker_id} add timer 5000ms");
     }
 }
Beispiel #3
0
 function onStart(\swoole_server $serv, $worker_id)
 {
     $this->redis = new \redis();
     $this->redis->connect('localhost');
     $this->today = date("Y-m-d");
     $this->log_table = 'logs_' . $this->today;
     $this->tomorrow = date("Y-m-d", time() + 86400);
     \Swoole::$php->db->query("CREATE TABLE IF NOT EXISTS `logs_" . $this->today . "` LIKE `logs`");
     \Swoole::$php->db->query("CREATE TABLE IF NOT EXISTS `logs_" . $this->tomorrow . "` LIKE `logs`");
     //每个worker 24小时执行一次创建表 不要零点启动服务
     $serv->addtimer(24 * 60 * 60000);
 }
Beispiel #4
0
function setTimerInWorker(swoole_server $serv, $worker_id)
{
    if ($worker_id == 0) {
        echo "Start: " . microtime(true) . "\n";
        $serv->addtimer(3000);
        $serv->addtimer(7000);
        //var_dump($serv->gettimer());
    }
    $serv->after(2000, function () {
        echo "Timeout: " . microtime(true) . "\n";
    });
    $serv->after(5000, function () {
        echo "Timeout: " . microtime(true) . "\n";
        global $serv;
        $serv->deltimer(3000);
    });
}
Beispiel #5
0
 public function onConnect(swoole_server $server, $fd, $fromId)
 {
     $log_file = $server->setting['log_file'];
     $pid_file = str_replace('.log', ".pid", $log_file);
     if (file_exists($pid_file)) {
         $fp = fopen("{$pid_file}", "r");
         $re = fread($fd, filesize($pid_file));
     } else {
         //$masterPid = $server->master_pid;
         $masterPid = $server->manager_pid;
         $fp = fopen("{$pid_file}", "w+");
         $re = fwrite($fp, $masterPid);
     }
     if ($re) {
         //$this->_addtask($server);
         $server->addtimer(10000);
     }
 }
Beispiel #6
0
function my_onReceive(swoole_server $serv, $fd, $from_id, $data)
{
    my_log("Worker#{$serv->worker_pid} Client[{$fd}@{$from_id}]: received: {$data}");
    $cmd = trim($data);
    if ($cmd == "reload") {
        $serv->reload();
    } elseif ($cmd == "task") {
        $task_id = $serv->task("task-" . $fd);
        echo "Dispath AsyncTask: id={$task_id}\n";
    } elseif ($cmd == "taskwait") {
        $result = $serv->taskwait("taskwait");
        if ($result) {
            $serv->send($fd, "taskwaitok");
        }
        echo "SyncTask: result=" . var_export($result, true) . "\n";
    } elseif ($cmd == "hellotask") {
        $serv->task("hellotask");
    } elseif ($cmd == "sendto") {
        $serv->sendto("127.0.0.1", 9999, "hello world");
    } elseif ($cmd == "close") {
        $serv->send($fd, "close connection\n");
        $result = $serv->close($fd);
    } elseif ($cmd == "info") {
        $info = $serv->connection_info(strval($fd), $from_id);
        var_dump($info["remote_ip"]);
        $serv->send($fd, 'Info: ' . var_export($info, true) . PHP_EOL);
    } elseif ($cmd == 'proxy') {
        $serv->send(1, "hello world\n");
    } elseif ($cmd == 'sleep') {
        sleep(10);
    } elseif ($cmd == 'foreach') {
        foreach ($serv->connections as $fd) {
            echo "conn : {$fd}\n";
        }
        return;
    } elseif ($cmd == 'tick') {
        $serv->tick(2000, function ($id) {
            echo "tick #{$id}\n";
        });
    } elseif ($cmd == 'addtimer') {
        $serv->addtimer(3000);
    } elseif ($cmd == "list") {
        $start_fd = 0;
        echo "broadcast\n";
        while (true) {
            $conn_list = $serv->connection_list($start_fd, 10);
            if (empty($conn_list)) {
                echo "iterates finished\n";
                break;
            }
            $start_fd = end($conn_list);
            var_dump($conn_list);
        }
    } elseif ($cmd == "list2") {
        foreach ($serv->connections as $con) {
            var_dump($serv->connection_info($con));
        }
    } elseif ($cmd == "stats") {
        $serv_stats = $serv->stats();
        $serv->send($fd, 'Stats: ' . var_export($serv_stats, true) . PHP_EOL);
    } elseif ($cmd == "broadcast") {
        broadcast($serv, $fd, "hello from {$fd}\n");
    } elseif ($cmd == "error") {
        hello_no_exists();
    } elseif ($cmd == "exit") {
        exit("worker php exit.\n");
    } elseif (substr($cmd, 0, 5) == "close") {
        $close_fd = substr($cmd, 6);
        $serv->close($close_fd);
    } elseif ($cmd == "shutdown") {
        $serv->shutdown();
    } elseif ($cmd == 'sendbuffer') {
        $buffer = G::getBuffer($fd);
        $buffer->append("hello\n");
        $serv->send($fd, $buffer);
    } else {
        $ret = $serv->send($fd, 'Swoole: ' . $data, $from_id);
        var_dump($ret);
        //$serv->close($fd);
    }
    //echo "Client:Data. fd=$fd|from_id=$from_id|data=$data";
    //    $serv->after(
    //        800, function () {
    //            echo "hello";
    //        }
    //    );
    //swoole_server_send($serv, $other_fd, "Server: $data", $other_from_id);
}
Beispiel #7
0
function StartServSock($RunServer)
{
    cli_set_process_title(SuperProcessName);
    //这边其实也是也是demon进程
    $serv = new swoole_server(uniSockPath, 0, SWOOLE_BASE, SWOOLE_UNIX_STREAM);
    //维持一个动态数组 实现动态监控server 包含了php的启动路径和停止路径 array('php'=>,'name'=)
    $serv->runServer = $RunServer;
    $serv->set(array('worker_num' => 1, 'daemonize' => true));
    $serv->on('WorkerStart', function ($serv, $workerId) {
        //监控周期
        $serv->addtimer(1000);
    });
    error_log(PHP_EOL . __LINE__ . PHP_EOL, 3, '/tmp/SuperMaster.log');
    //定时器中操作 主要为轮巡 启动服务
    $serv->on('Timer', function ($serv, $interval) {
        StartLogTimer(__LINE__ . 'timer start ' . time());
        if (empty($serv->runServer)) {
            StartLogTimer(__LINE__ . ' ' . 'no server is running ' . PHP_EOL);
            return;
        }
        foreach ($serv->runServer as $serverName) {
            $ret = system("ps aux | grep " . $serverName['name'] . " | grep master | grep -v grep ");
            StartLogTimer(__LINE__ . ' cmd is ' . "ps aux | grep " . $serverName['name'] . " | grep master | grep -v grep " . print_r($ret, true));
            if (empty($ret)) {
                //挂了 什么都没有  之后可能要通过数量来获取
                //todo
                StartServ($serverName['php'], 'start', $serverName['name']);
                StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serverName, true) . ' server is dead , start to restart');
            } else {
                StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serverName, true) . ' server is running success');
            }
        }
        StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serv->runServer, true) . ' server is dead , start to restart');
    });
    error_log(PHP_EOL . __LINE__ . PHP_EOL, 3, '/tmp/SuperMaster.log');
    $serv->on('connect', function ($serv, $fd, $from_id) {
        echo "[#" . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Connect.\n";
    });
    error_log(PHP_EOL . __LINE__ . PHP_EOL, 3, '/tmp/SuperMaster.log');
    $serv->on('receive', function ($serv, $fd, $from_id, $data) {
        StartLog(__LINE__ . 'receive data is' . print_r($data, true));
        $opData = json_decode($data, true);
        if ($opData['cmd'] == 'start') {
            //添加到runserver  还是需要获取路径 存入数组中
            if (isset($serv->runServer[$opData['server']])) {
                //如果已经有了,说明服务已经启动
                $serv->send($fd, json_encode(array('r' => 1, "msg" => $opData['server'] . ' is already running')));
                StartLog(__LINE__ . 'receive data is' . json_encode(array('r' => 1, "msg" => $opData['server'] . ' is already running')));
                return;
            }
            //如果没有,则读取配置  todo 回调中是否可以执行 getServerIni?  验证了可以
            $retConf = getServerIni($opData['server']);
            if ($retConf['r'] != 0) {
                //
                $serv->send($fd, json_encode($retConf));
                return;
            } else {
                //正常启动
                $phpStart = $retConf['conf']['server']['php'];
                StartServ($phpStart, 'start', $opData['server']);
                StartLog(__LINE__ . " {$phpStart} " . STARTBASEPATH . "/lib/Swoole/shell/start.php " . $opData['cmd'] . ' ' . $opData['server']);
                $serv->runServer[$opData['server']] = array('php' => $phpStart, 'name' => $opData['server']);
                //添加到runServer中
                $serv->send($fd, json_encode(array('r' => 0, 'msg' => 'server start success')));
                return;
            }
        } elseif ($opData['cmd'] == 'stop') {
            //从runserver中干掉
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            unset($serv->runServer[$opData['server']]);
            StartLog(__LINE__ . 'THIS RUNSERVER IS' . print_r($serv->runServer, true));
            StartServ($phpStart, 'stop', $opData['server']);
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . "/lib/Swoole/shell/start.php " . $opData['cmd'] . ' ' . $opData['server']);
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => 'server stop success')));
            return;
        } elseif ($opData['cmd'] == 'status') {
            //获取所有服务的状态
            StartLog(__LINE__ . json_encode(array('r' => 0, 'msg' => 'server running success ' . print_r($serv->runServer, true))));
            $serv->send($fd, json_encode(array('r' => 0, 'data' => $serv->runServer)));
            return;
        } elseif ($opData['cmd'] == 'shutdown') {
            //获取所有服务的状态
            StartLog(__LINE__ . json_encode(array('r' => 0, 'msg' => 'server running success ' . print_r($serv->runServer, true))));
            $serv->send($fd, json_encode(array('r' => 0, 'data' => $serv->runServer)));
            //清除所有的runServer序列
            unset($serv->runServer);
            return;
        } elseif ($opData['cmd'] == 'reload') {
            //重载所有服务
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . "/lib/Swoole/shell/start.php " . $opData['cmd'] . ' ' . $opData['server']);
            StartServ($phpStart, 'reload', $opData['server']);
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => 'server start success')));
            return;
        } elseif ($opData['cmd'] == 'restart') {
            //重启所有服务
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            //首先unset 防止被自动拉起,然后停止,然后sleep 然后start
            unset($serv->runServer[$opData['server']]);
            //从runserver中干掉
            StartServ($phpStart, 'stop', $opData['server']);
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . "/lib/Swoole/shell/start.php " . ' stop ' . $opData['server']);
            sleep(2);
            //   exec("$phpStart ".STARTBASEPATH . "/lib/Swoole/shell/start.php ".' start '.$opData['server']);//
            StartServ($phpStart, 'start', $opData['server']);
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . "/lib/Swoole/shell/start.php " . ' start ' . $opData['server']);
            $serv->runServer[$opData['server']] = array('php' => $phpStart, 'name' => $opData['server']);
            //添加到runServer中
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => 'server restart success')));
            return;
        }
    });
    $serv->on('close', function ($serv, $fd, $from_id) {
        echo "[#" . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Close.\n";
    });
    $serv->start();
    //之后不会再执行任何代码
}
Beispiel #8
0
    $data = intval($data);
    for ($i = 0; $i < $data; $i++) {
        $tid = mt_rand(0, 1);
        echo "data:{$i} to task: {$tid} " . PHP_EOL;
        $serv->task($i, $tid);
    }
});
$serv->on('Task', function (swoole_server $serv, $task_id, $from_id, $data) {
    echo "onTask: [PID=" . posix_getpid() . "]: task_id={$task_id}, data_len=" . strlen($data) . "." . PHP_EOL;
    sleep(10);
    //$serv->finish($data);
    echo 'finish' . PHP_EOL;
    return;
});
$serv->on('Finish', function (swoole_server $serv, $task_id, $data) {
    echo "Task#{$task_id} finished, data_len=" . strlen($data) . PHP_EOL;
});
$serv->on('Timer', function (swoole_server $serv, $time) {
    echo "{$time} call" . PHP_EOL;
    print_r($serv->stats());
});
$serv->on('workerStart', function ($serv, $worker_id) {
    global $argv;
    if ($worker_id >= $serv->setting['worker_num']) {
        swoole_set_process_name("php {$argv[0]}: task_worker");
    } else {
        $serv->addtimer(5000);
        swoole_set_process_name("php {$argv[0]}: worker");
    }
});
$serv->start();
<?php

$serv = new swoole_server("0.0.0.0", 10000);
$serv->set(array('worker_num' => 8));
$serv->on('timer', function ($serv, $interval) {
    echo "onTimer: {$interval}\n";
});
$serv->on('workerStart', function ($serv, $worker_id) {
    if ($worker_id == 0) {
        $serv->addtimer(300);
    }
});
$serv->on('connect', function ($serv, $fd) {
    $serv->send($fd, filesize(__DIR__ . '/test.jpg'));
    echo "Client:Connect.\n";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    echo "Client[{$fd}]: {$data}\n";
    $serv->sendfile($fd, __DIR__ . '/test.jpg');
    //$serv->close($fd);
});
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});
$serv->start();
Beispiel #10
0
// 设置自身node id
$nid = Base::get_node_id();
// 初始化路由器
$table = array();
// 最后请求时间
$last_find = time();
// 保存线程列表
$threads = [];
// 长期在线node
$bootstrap_nodes = array(array('router.bittorrent.com', 6881), array('dht.transmissionbt.com', 6881), array('router.utorrent.com', 6881), array('208.67.16.113', 8000), array('open.acgtracker.com', 1096), array('t2.popgo.org', 7456));
LOGI("DHT 爬虫服务启动");
$serv = new swoole_server('0.0.0.0', 6882, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);
$serv->set(array('worker_num' => WORKER_NUM, 'daemonize' => FALSE, 'max_request' => MAX_REQUEST, 'dispatch_mode' => 2, 'log_file' => ABSPATH . 'error.log'));
$serv->on('WorkerStart', function ($serv, $worker_id) {
    // 添加一个定时器, 使服务器定时寻找节点
    $serv->addtimer(AUTO_FIND_TIME);
    auto_find_node();
});
$serv->on('Receive', function ($serv, $fd, $from_id, $data) {
    // 检查数据长度
    if (strlen($data) == 0) {
        return false;
    }
    // 对数据进行解码
    $msg = Base::decode($data);
    // 获取对端链接信息, udp链接需要加上$from_id参数
    $fdinfo = $serv->connection_info($fd, $from_id);
    // 对接收到的数据进行类型判断
    if (!isset($msg['y'])) {
        /// 数据格式不合法
        /// 什么都不做
Beispiel #11
0
function StartServSock($RunServer)
{
    cli_set_process_title(SuperProcessName);
    //这边其实也是也是demon进程
    $serv = new swoole_server(uniSockPath, 0, SWOOLE_BASE, SWOOLE_UNIX_STREAM);
    //维持一个动态数组 实现动态监控server 包含了php的启动路径和停止路径 array('php'=>,'name'=)
    $serv->runServer = $RunServer;
    $serv->set(array('worker_num' => 1, 'daemonize' => true));
    $serv->on('WorkerStart', function ($serv, $workerId) {
        //监控周期
        $serv->addtimer(1000);
    });
    //定时器中操作 主要为轮巡 启动服务
    $serv->on('Timer', function ($serv, $interval) {
        StartLogTimer(__LINE__ . 'timer start ' . time());
        if (empty($serv->runServer)) {
            StartLogTimer(__LINE__ . ' ' . 'no server is running ' . PHP_EOL);
            return;
        }
        foreach ($serv->runServer as $serverName) {
            $ret = system("ps aux | grep " . $serverName['name'] . " | grep master | grep -v grep ");
            StartLogTimer(__LINE__ . ' cmd is ' . "ps aux | grep " . $serverName['name'] . " | grep master | grep -v grep " . json_encode($ret));
            if (empty($ret)) {
                //挂了 什么都没有  之后可能要通过数量来获取
                StartServ($serverName['php'], 'start', $serverName['name']);
                StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . json_encode($serverName, true) . ' server is dead , start to restart' . PHP_EOL);
            } else {
                StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . json_encode($serverName, true) . ' server is running success' . PHP_EOL);
            }
        }
    });
    $serv->on('connect', function ($serv, $fd, $from_id) {
        echo "[#" . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Connect.\n";
    });
    $serv->on('receive', function ($serv, $fd, $from_id, $data) {
        StartLog(__LINE__ . 'receive data is' . print_r($data, true));
        $opData = json_decode($data, true);
        switch ($opData['cmd']) {
            case 'start':
                if (isset($serv->runServer[$opData['server']])) {
                    //如果已经有了,说明服务已经启动
                    $serv->send($fd, json_encode(['r' => 1, "msg" => $opData['server'] . ' is already running']));
                    StartLog(__LINE__ . 'receive data is' . json_encode(['r' => 1, "msg" => $opData['server'] . ' is already running']));
                    return;
                }
                //如果没有,则读取配置
                $retConf = getServerConfig($opData['server']);
                if ($retConf['r'] != 0) {
                    //
                    $serv->send($fd, json_encode($retConf));
                    return;
                } else {
                    //正常启动
                    $phpStart = $retConf['conf']['server']['php'];
                    StartServ($phpStart, 'start', $opData['server']);
                    StartLog(__LINE__ . " {$phpStart} " . __DIR__ . "/start.php " . $opData['cmd'] . ' ' . $opData['server']);
                    $serv->runServer[$opData['server']] = ['php' => $phpStart, 'name' => $opData['server']];
                    //添加到runServer中
                    $serv->send($fd, json_encode(['r' => 0, 'msg' => "server {$opData['server']} start" . "  [SUCCESS] "]));
                    return;
                }
            case 'stop':
                $phpStart = $serv->runServer[$opData['server']]['php'];
                //获取php启动路径
                unset($serv->runServer[$opData['server']]);
                StartLog(__LINE__ . 'THIS RUNSERVER IS' . print_r($serv->runServer, true));
                StartServ($phpStart, 'stop', $opData['server']);
                StartLog(__LINE__ . " {$phpStart} " . __DIR__ . "/start.php " . $opData['cmd'] . ' ' . $opData['server']);
                $serv->send($fd, json_encode(['r' => 0, 'msg' => "server {$opData['server']} stop " . "  [SUCCESS] "]));
                return;
            case 'status':
                //获取所有服务的状态
                StartLog(__LINE__ . " cmd is status " . print_r($serv->runServer, true));
                $serv->send($fd, json_encode(['r' => 0, 'data' => $serv->runServer]));
                return;
            case 'shutdown':
                StartLog(__LINE__ . " cmd is shutdown " . print_r($serv->runServer, true));
                $serv->send($fd, json_encode(['r' => 0, 'data' => $serv->runServer]));
                //清除所有的runServer序列
                unset($serv->runServer);
                return;
            case 'reload':
                $phpStart = $serv->runServer[$opData['server']]['php'];
                //获取php启动路径
                StartLog(__LINE__ . "{$phpStart} " . __DIR__ . "/start.php " . $opData['cmd'] . ' ' . $opData['server']);
                StartServ($phpStart, 'reload', $opData['server']);
                $serv->send($fd, json_encode(['r' => 0, 'msg' => "server {$opData['server']}  reload " . "  [SUCCESS] "]));
                return;
            case 'restart':
                $phpStart = $serv->runServer[$opData['server']]['php'];
                //获取php启动路径
                //首先unset 防止被自动拉起,然后停止,然后sleep 然后start
                unset($serv->runServer[$opData['server']]);
                //从runserver中干掉
                StartServ($phpStart, 'stop', $opData['server']);
                StartLog(__LINE__ . "{$phpStart} " . __DIR__ . "/start.php " . ' stop ' . $opData['server']);
                sleep(2);
                StartServ($phpStart, 'start', $opData['server']);
                StartLog(__LINE__ . "{$phpStart} " . __DIR__ . "/start.php " . ' start ' . $opData['server']);
                $serv->runServer[$opData['server']] = ['php' => $phpStart, 'name' => $opData['server']];
                //添加到runServer中
                $serv->send($fd, json_encode(['r' => 0, 'msg' => "server {$opData['server']} restart   [SUCCESS] "]));
                return;
        }
    });
    $serv->on('close', function ($serv, $fd, $from_id) {
        echo "[#" . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Close.\n";
        StartLog(__LINE__ . SuperProcessName . " begin to close ");
    });
    $serv->start();
    //之后不会再执行任何代码
}
Beispiel #12
0
 function onStart(\swoole_server $serv, $worker_id)
 {
     $this->worker_id = $worker_id;
     if ($this->worker_id <= $this->setting['worker_num'] - 1) {
         swoole_set_process_name(self::PROCESS_NAME . ": worker #{$worker_id}");
         $serv->addtimer($this->recyle_time);
         if (isset($this->setting['worker_dump_file'])) {
             $dump_file = $this->setting['worker_dump_file'] . "_" . $worker_id;
             if (file_exists($dump_file)) {
                 $this->count = unserialize(file_get_contents($dump_file));
                 $this->log("load worker {$worker_id} data from last :" . print_r($this->count, 1));
                 unlink($dump_file);
             }
         }
     } else {
         swoole_set_process_name(self::PROCESS_NAME . ": task #{$worker_id}");
         $serv->addtimer($this->insert_time);
         if (isset($this->setting['task_dump_file'])) {
             $dump_file = $this->setting['task_dump_file'] . "_" . $worker_id;
             if (file_exists($dump_file)) {
                 $this->task_count = unserialize(file_get_contents($dump_file));
                 $this->log("load task {$worker_id} data from last :" . print_r($this->task_count, 1));
                 unlink($dump_file);
             }
         }
     }
 }
Beispiel #13
0
function StartServSock($RunServer)
{
    cli_set_process_title(SuperProcessName);
    //这边其实也是也是demon进程
    $serv = new swoole_server(uniSockPath, 0, SWOOLE_BASE, SWOOLE_UNIX_STREAM);
    //维持一个动态数组 实现动态监控server 包含了php的启动路径和停止路径 array('php'=>,'name'=)
    $serv->runServer = $RunServer;
    $serv->set(array('worker_num' => 1, 'daemonize' => true));
    $serv->on('WorkerStart', function ($serv, $workerId) {
        // 只有当worker_id为0时才添加定时器,避免重复添加
        if ($workerId == 0) {
            // 定时任务, 100ms检测一次任务队列
            // 从redis导入队列
            /*$serv->tick(100, function($id, $server) {
                    $server->task(
                      json_encode(array(
            
                      ));
                    );
                   queueLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serv, true) . ' queue');
                  });*/
            // 监控周期
            $serv->addtimer(1000);
        }
    });
    //定时器中操作 主要为轮巡 启动服务
    $serv->on('Timer', function ($serv, $interval) {
        StartLogTimer(__LINE__ . 'timer start ' . time());
        if (empty($serv->runServer)) {
            StartLogTimer(__LINE__ . ' ' . 'no server is running ' . PHP_EOL);
            return;
        }
        switch ($interval) {
            // for 100ms
            case 100:
                queueLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serverName, true) . ' queue');
                break;
                // for 1000ms
            // for 1000ms
            default:
                foreach ($serv->runServer as $serverName) {
                    $ret = system('ps aux | grep ' . $serverName['name'] . ' | grep master | grep -v grep ');
                    StartLogTimer(__LINE__ . ' cmd is ' . 'ps aux | grep ' . $serverName['name'] . ' | grep master | grep -v grep ' . print_r($ret, true));
                    if (empty($ret)) {
                        //挂了 什么都没有  之后可能要通过数量来获取
                        //todo
                        StartServ($serverName['php'], 'start', $serverName['name']);
                        StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serverName, true) . ' server is dead , start to restart' . PHP_EOL);
                    } else {
                        StartLogTimer(__LINE__ . date('Y-m-d H:i:s') . '  ' . print_r($serverName, true) . ' server is running success' . PHP_EOL);
                    }
                }
                break;
        }
    });
    $serv->on('connect', function ($serv, $fd, $from_id) {
        echo '[#' . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Connect.\n";
    });
    $serv->on('receive', function ($serv, $fd, $from_id, $data) {
        StartLog(__LINE__ . 'receive data is' . print_r($data, true));
        $opData = json_decode($data, true);
        if ($opData['cmd'] == 'start') {
            //添加到runserver  还是需要获取路径 存入数组中
            if (isset($serv->runServer[$opData['server']])) {
                //如果已经有了,说明服务已经启动
                $serv->send($fd, json_encode(array('r' => 1, 'msg' => $opData['server'] . ' is already running')));
                StartLog(__LINE__ . 'receive data is' . json_encode(array('r' => 1, 'msg' => $opData['server'] . ' is already running')));
                return;
            }
            //如果没有,则读取配置
            $retConf = getServerIni($opData['server']);
            if ($retConf['r'] != 0) {
                //
                $serv->send($fd, json_encode($retConf));
                return;
            } else {
                //正常启动
                $phpStart = $retConf['conf']['server']['php'];
                StartServ($phpStart, 'start', $opData['server']);
                StartLog(__LINE__ . " {$phpStart} " . STARTBASEPATH . '/lib/Swoole/shell/start.php ' . $opData['cmd'] . ' ' . $opData['server']);
                $serv->runServer[$opData['server']] = array('php' => $phpStart, 'name' => $opData['server']);
                //添加到runServer中
                $serv->send($fd, json_encode(array('r' => 0, 'msg' => "server {$opData['server']} start" . '  [SUCCESS] ')));
                return;
            }
        } elseif ($opData['cmd'] == 'stop') {
            //从runserver中干掉
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            unset($serv->runServer[$opData['server']]);
            StartLog(__LINE__ . 'THIS RUNSERVER IS' . print_r($serv->runServer, true));
            StartServ($phpStart, 'stop', $opData['server']);
            StartLog(__LINE__ . " {$phpStart} " . STARTBASEPATH . '/lib/Swoole/shell/start.php ' . $opData['cmd'] . ' ' . $opData['server']);
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => "server {$opData['server']} stop " . '  [SUCCESS] ')));
            return;
        } elseif ($opData['cmd'] == 'status') {
            //获取所有服务的状态
            StartLog(__LINE__ . ' cmd is status ' . print_r($serv->runServer, true));
            $serv->send($fd, json_encode(array('r' => 0, 'data' => $serv->runServer)));
            return;
        } elseif ($opData['cmd'] == 'shutdown') {
            //获取所有服务的状态
            StartLog(__LINE__ . ' cmd is shutdown ' . print_r($serv->runServer, true));
            $serv->send($fd, json_encode(array('r' => 0, 'data' => $serv->runServer)));
            //清除所有的runServer序列
            unset($serv->runServer);
            return;
        } elseif ($opData['cmd'] == 'reload') {
            //重载所有服务
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . '/lib/Swoole/shell/start.php ' . $opData['cmd'] . ' ' . $opData['server']);
            StartServ($phpStart, 'reload', $opData['server']);
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => "server {$opData['server']}  reload " . '  [SUCCESS] ')));
            return;
        } elseif ($opData['cmd'] == 'restart') {
            //重启所有服务
            $phpStart = $serv->runServer[$opData['server']]['php'];
            //获取php启动路径
            //首先unset 防止被自动拉起,然后停止,然后sleep 然后start
            unset($serv->runServer[$opData['server']]);
            //从runserver中干掉
            StartServ($phpStart, 'stop', $opData['server']);
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . '/lib/Swoole/shell/start.php ' . ' stop ' . $opData['server']);
            sleep(2);
            //   exec("$phpStart ".STARTBASEPATH . "/lib/Swoole/shell/start.php ".' start '.$opData['server']);//
            StartServ($phpStart, 'start', $opData['server']);
            StartLog(__LINE__ . "{$phpStart} " . STARTBASEPATH . '/lib/Swoole/shell/start.php ' . ' start ' . $opData['server']);
            $serv->runServer[$opData['server']] = array('php' => $phpStart, 'name' => $opData['server']);
            //添加到runServer中
            $serv->send($fd, json_encode(array('r' => 0, 'msg' => "server {$opData['server']} restart   [SUCCESS] ")));
            return;
        }
    });
    $serv->on('close', function ($serv, $fd, $from_id) {
        echo '[#' . posix_getpid() . "]\tClient@[{$fd}:{$from_id}]: Close.\n";
        StartLog(__LINE__ . SuperProcessName . ' begin to close ');
    });
    $serv->start();
}
Beispiel #14
0
<?php

$serv = new swoole_server("0.0.0.0", 9501);
$serv->set(array('worker_num' => 1, 'ipc_mode' => SWOOLE_IPC_MSGQUEUE, 'message_queue_key' => ftok(__FILE__, 0)));
$serv->on('timer', function ($serv, $interval) {
    echo "onTimer: {$interval}\n";
});
$serv->on('workerStart', function ($serv, $worker_id) {
    global $argv;
    swoole_set_process_name("php {$argv[0]}: worker");
    if ($worker_id == 0) {
        $serv->addtimer(1000);
    }
});
$serv->on('connect', function ($serv, $fd, $from_id) {
    //echo "[#".posix_getpid()."]\tClient@[$fd:$from_id]: Connect.\n";
});
$serv->on('receive', function (swoole_server $serv, $fd, $from_id, $data) {
    //echo "[#".posix_getpid()."]\tClient[$fd]: $data\n";
    $serv->send($fd, json_encode(array("hello" => '1213', "bat" => "ab")) . PHP_EOL);
    //$serv->close($fd);
});
$serv->on('close', function ($serv, $fd, $from_id) {
    //echo "[#".posix_getpid()."]\tClient@[$fd:$from_id]: Close.\n";
});
$serv->start();
Beispiel #15
0
 /**
  * 主调用函数
  */
 public function main()
 {
     $serv = new swoole_server($this->host, $this->port);
     $serv->set(array('worker_num' => $this->works, 'daemonize' => $this->daemonize, 'log_file' => $this->logFile, 'heartbeat_check_interval' => $this->hbInterval, 'heartbeat_idle_time' => $this->hbIdle, 'reactor_num' => $this->pollNum, 'writer_num' => $this->writerNum, 'max_request' => $this->maxRequest, 'dispatch_mode' => $this->dispatch_mode));
     $serv->on('Start', function ($serv) {
         echo 'Swoole Server running', "\n";
         swoole_set_process_name('swoole master');
     });
     $serv->on('Timer', array($this, 'onTimer'));
     $serv->on('WorkerStart', function ($serv, $worker_id) {
         if ($worker_id >= $serv->setting['worker_num']) {
             swoole_set_process_name("swoole task worker, worker_id: " . $serv->worker_id);
         } else {
             swoole_set_process_name("swoole event worker, worker_id: " . $serv->worker_id);
         }
         if ($worker_id == 0) {
             $serv->addtimer(3600000);
         }
     });
     $serv->on('ManagerStart', function ($serv) {
         swoole_set_process_name("swoole manager worker");
     });
     $serv->on('connect', array($this, 'onConnect'));
     $serv->on('receive', array($this, 'onReceive'));
     $serv->on('close', array($this, 'onClose'));
     $this->serv = $serv;
     $serv->start();
 }
Beispiel #16
0
function my_onReceive(swoole_server $serv, $fd, $from_id, $data)
{
    my_log("Worker#{$serv->worker_pid} Client[{$fd}@{$from_id}]: received: {$data}");
    $cmd = trim($data);
    if ($cmd == "reload") {
        $serv->reload();
    } elseif ($cmd == "task") {
        $task_id = $serv->task("task " . $fd);
        echo "Dispath AsyncTask: id={$task_id}\n";
    } elseif ($cmd == "taskclose") {
        $serv->task("close " . $fd);
        echo "close the connection in taskworker\n";
    } elseif ($cmd == "tasksend") {
        $serv->task("send " . $fd);
    } elseif ($cmd == "bigtask") {
        $serv->task(str_repeat('A', 8192 * 5));
    } elseif ($cmd == "taskwait") {
        $result = $serv->taskwait("taskwait");
        if ($result) {
            $serv->send($fd, "taskwaitok");
        }
        echo "SyncTask: result=" . var_export($result, true) . "\n";
    } elseif ($cmd == "taskWaitMulti") {
        $result = $serv->taskWaitMulti(array(str_repeat('A', 8192 * 5), str_repeat('B', 8192 * 6), str_repeat('C', 8192 * 8)));
        if ($result) {
            $resp = "taskWaitMulti ok\n";
            foreach ($result as $k => $v) {
                $resp .= "result[{$k}] length=" . strlen($v) . "\n";
            }
            $serv->send($fd, $resp);
        } else {
            $serv->send($fd, "taskWaitMulti error\n");
        }
    } elseif ($cmd == "hellotask") {
        $serv->task("hellotask");
    } elseif ($cmd == "taskcallback") {
        $serv->task("taskcallback", -1, function (swoole_server $serv, $task_id, $data) {
            echo "Task Callback: ";
            var_dump($task_id, $data);
        });
    } elseif ($cmd == "sendto") {
        $serv->sendto("127.0.0.1", 9999, "hello world");
    } elseif ($cmd == "close") {
        $serv->send($fd, "close connection\n");
        $result = $serv->close($fd);
    } elseif ($cmd == "info") {
        $info = $serv->connection_info(strval($fd), $from_id);
        var_dump($info["remote_ip"]);
        $serv->send($fd, 'Info: ' . var_export($info, true) . PHP_EOL);
    } elseif ($cmd == 'proxy') {
        $serv->send(1, "hello world\n");
    } elseif ($cmd == 'sleep') {
        sleep(10);
    } elseif ($cmd == 'foreach') {
        foreach ($serv->connections as $fd) {
            echo "conn : {$fd}\n";
        }
        return;
    } elseif ($cmd == 'tick') {
        $serv->tick(2000, function ($id) {
            echo "tick #{$id}\n";
        });
    } elseif ($cmd == 'addtimer') {
        $serv->addtimer(3000);
    } elseif ($cmd == "list") {
        $start_fd = 0;
        echo "broadcast\n";
        while (true) {
            $conn_list = $serv->connection_list($start_fd, 10);
            if (empty($conn_list)) {
                echo "iterates finished\n";
                break;
            }
            $start_fd = end($conn_list);
            var_dump($conn_list);
        }
    } elseif ($cmd == "list2") {
        foreach ($serv->connections as $con) {
            var_dump($serv->connection_info($con));
        }
    } elseif ($cmd == "stats") {
        $serv_stats = $serv->stats();
        $serv->send($fd, 'Stats: ' . var_export($serv_stats, true) . "\ncount=" . count($serv->connections) . PHP_EOL);
    } elseif ($cmd == "broadcast") {
        broadcast($serv, $fd, "hello from {$fd}\n");
    } elseif ($cmd == "error") {
        hello_no_exists();
    } elseif ($cmd == "exit") {
        exit("worker php exit.\n");
    } elseif ($cmd == 'pause') {
        echo "pause receive data. fd={$fd}\n";
        $serv->pause($fd);
    } elseif (substr($cmd, 0, 6) == "resume") {
        $resume_fd = substr($cmd, 7);
        $serv->resume($resume_fd);
    } elseif (substr($cmd, 0, 5) == "close") {
        $close_fd = substr($cmd, 6);
        $serv->close($close_fd);
    } elseif ($cmd == "shutdown") {
        $serv->shutdown();
    } elseif ($cmd == "fatalerror") {
        require __DIR__ . '/php/error.php';
    } elseif ($cmd == 'sendbuffer') {
        $buffer = G::getBuffer($fd);
        $buffer->append("hello\n");
        $serv->send($fd, $buffer);
    } elseif ($cmd == 'defer') {
        $serv->defer(function () use($fd, $serv) {
            $serv->close($fd);
            $serv->defer(function () {
                echo "deferd\n";
            });
        });
        $serv->send($fd, 'Swoole: ' . $data, $from_id);
    } else {
        $serv->send($fd, 'Swoole: ' . $data, $from_id);
        //$serv->close($fd);
    }
    //echo "Client:Data. fd=$fd|from_id=$from_id|data=$data";
    //    $serv->after(
    //        800, function () {
    //            echo "hello";
    //        }
    //    );
    //swoole_server_send($serv, $other_fd, "Server: $data", $other_from_id);
}