今天我们来安装和测试一下php的多并发高性能网络通信扩展,这个扩展是使用C语音开发的,加载到PHP以后,在PHP的层面上实现了多并发异步通信,模拟了go语音的很多特性,极大的拓宽了PHP的应用场景。
直接使用官网上的那句命令就可以,安装swoole时可能会出现错误和卡住不动,多试几次就能成功。 pecl install swoole 要配置php的cli环境和fpm环境的ini文件,把扩展的so加载进去。
视频地址:
https://www.bilibili.com/video/av70354024/
httpServer.php
代码语言:javascript复制$http = new swoole_http_server("127.0.0.1", 9501);
$http->on("start", function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9501n";
});
$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello Worldn");
});
$http->start();
注意使用httpClient的时候会有一些错误,首先新版的swoole移除了SwooleHttpClient,会报类找不到,其次要在协程中执行get方法
httpClient.php
代码语言:javascript复制$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function($cli) {
$cli->send("hello worldn");
});
$client->on("receive", function($cli, $data){
echo "received: {$data}n";
});
$client->on("error", function($cli){
echo "connect failedn";
});
$client->on("close", function($cli){
echo "connection closen";
});
$client->connect("127.0.0.1", 9502, 0.5);
taskServer.php
代码语言:javascript复制<?php
$serv = new SwooleServer("127.0.0.1", 9502, SWOOLE_BASE);
$serv->set(array(
'worker_num' => 2,
'task_worker_num' => 4,
));
$serv->on('Receive', function(SwooleServer $serv, $fd, $from_id, $data) {
echo "接收数据" . $data . "n";
$data = trim($data);
$task_id = $serv->task($data, 0);
$serv->send($fd, "分发任务,任务id为$task_idn");
});
$serv->on('Task', function (SwooleServer $serv, $task_id, $from_id, $data) {
echo "Tasker进程接收到数据";
echo "#{$serv->worker_id}tonTask: [PID={$serv->worker_pid}]: task_id=$task_id, data_len=".strlen($data).".".PHP_EOL;
$serv->finish($data);
});
$serv->on('Finish', function (SwooleServer $serv, $task_id, $data) {
echo "Task#$task_id finished, data_len=".strlen($data).PHP_EOL;
});
$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 {
swoole_set_process_name("php {$argv[0]}: worker");
}
});
$serv->start();
taskClient.php
代码语言:javascript复制$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function($cli) {
$cli->send("hello worldn");
});
$client->on("receive", function($cli, $data){
echo "received: {$data}n";
});
$client->on("error", function($cli){
echo "connect failedn";
});
$client->on("close", function($cli){
echo "connection closen";
});
$client->connect("127.0.0.1", 9502, 0.5);