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; } }
<?php //ini_set("swoole.aio_mode", 1); swoole_async_read(__DIR__ . '/data.txt', function ($filename, $content) { echo "file: {$filename}\ncontent-length: " . strlen($content) . "\nContent: {$content}\n"; if (empty($content)) { echo "file is end.\n"; return false; } else { return true; } }, 8192);
public function handelStaticFile($requestUrl, \swoole_http_response $respone) { $filename = Angel::app()->basePath . $requestUrl; if (is_file($filename)) { $mimeType = FileHelper::getMimeType($filename); if (empty($mimeType)) { $mimeType = 'text/html'; } $laseModifyTime = @filemtime($filename); if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $laseModifyTime) { $respone->status(304); Angel::app()->endend(); } else { if (filesize($filename) > self::MIN_GZIP_SIZE) { $respone->gzip(); } $respone->header('Content-Type', $mimeType); $respone->header('last-modified', $laseModifyTime); swoole_async_read($filename, function ($filename, $content) use($respone) { Angel::app()->end($content); }); } return true; } return false; }