public function onReceive(swoole_server $serv, $fd, $from_id, $data) { echo $serv->worker_pid . PHP_EOL; $case = intval($data); switch ($case) { case 1: swoole_async_readfile(__DIR__ . "/Test.txt", function ($filename, $content) { echo "{$filename}: {$content}"; }); break; case 2: swoole_async_writefile('test_2.log', "This is a test log", function ($filename) { echo "wirte ok.\n"; }); break; case 3: swoole_async_read(__DIR__ . "/Test.txt", function ($filename, $content) { if (empty($content)) { return false; } else { echo "{$filename}: {$content}"; return true; } }, 16); break; default: // 注:此处存在一个Bug,如果文件不存在并且没有指定offset(或者指定为-1),会引发一个错误。这里需要注意一下。 swoole_async_write('test_1.log', "This is a test log\n", -1, function ($filename, $writen) { var_dump(func_get_args()); }); break; } }
/** * @desc 管理服务启动 设置 manager 进程 ID * @param $server */ public function onManagerStart($server) { $logDir = $server->setting['pid_path']; if (!is_dir($logDir)) { mkdir($logDir, 0777, true); } $managerId = $server->manager_pid; swoole_set_process_name($server->setting['project_name'] . '_' . $server->setting['server_type'] . '_manager.pid'); $managerPidPath = $logDir . $server->setting['server_type'] . '_manager.pid'; \swoole_async_writefile($managerPidPath, $managerId); }
<?php swoole_async_writefile(__DIR__ . '/data2.txt', str_repeat('A', 1024) . "\n");
$serv = new swoole_server('0.0.0.0', 9094, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); $serv->set(['worker_num' => 1, 'task_worker_num' => 4, 'daemonize' => false, 'log_file' => '/tmp/swoole_udp_server.log']); $serv->on('receive', function (swoole_server $serv, $fd, $reactor_id, $data) { $task_id = $serv->task($data); $ymdhi = date('YmdHi'); swoole_async_write('/tmp/' . $ymdhi . '.txt', $data . "\n", -1); }); $serv->on('task', function ($serv, $task_id, $from_id, $data) { var_dump($serv->taskworker, $serv->worker_id, $serv->worker_pid); \ran\Ran::run($serv->worker_id, $data); return true; }); $serv->on('finish', function () { }); $serv->on('start', function ($serv) { swoole_async_writefile('/tmp/swoole_master_pid.log', $serv->master_pid, function ($filename) { }); // swoole_set_process_name("php swoole udp server master".$serv->master_pid); }); $serv->on('workerStart', function ($serv, $worker_id) { if ($worker_id >= $serv->setting['worker_num']) { //超过worker_num,表示这是一个task进程 // swoole_set_process_name("php swoole udp server tasker ".$worker_id); echo "{$worker_id} tasker start\n"; require './vendor/autoload.php'; } else { echo "{$worker_id} worker start\n"; // swoole_set_process_name("php swoole udp server worker ".$worker_id); } }); $serv->start();
<?php swoole_async_readfile(__DIR__ . '/../server.php', function ($filename, $content) { echo "file: {$filename}\ncontent-length: " . strlen($content) . "\nContent:\n"; swoole_async_writefile(__DIR__ . '/test.copy', $content, function ($write_file) { echo "file: {$write_file}\n"; swoole_event_exit(); }); });