服务器代码
先用cli方式启动服务器文件
<?php
$serv = new swoole_server("127.0.0.1", 9501);
//设置异步任务的工作进程数量
$serv->set(array('task_worker_num' => 4));
//监听数据接收事件
$serv->on('receive', function($serv, $fd, $from_id, $data) {
//投递异步任务
$task_id = $serv->task($data);//非阻塞
echo "同步代码执行完成\n";
});
//处理异步任务
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
handleFun($data);
//返回任务执行的结果
$serv->finish("finish");
});
//处理异步任务的结果
$serv->on('finish', function ($serv, $task_id, $data) {
echo "异步任务执行完成";
});
$serv->start();
function handleFun($data){
$value = null;
$arr = json_decode($data,true);
foreach ($arr as $value) {
mail($value['to'],$value['subject'],$value['content'],$value['headers']);
}
}
客户端代码
<?php
class Client
{
public function send($msg){
$client = new swoole_client(SWOOLE_SOCK_TCP);
//连接到服务器
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
$this->write("connect failed.");
}
//向服务器发送数据
if (!$client->send($msg))
{
$this->write("send ".$msg." failed.");
}
//关闭连接
$client->close();
}
private function write($str){
$path = "/tmp/synClient.log";
$str = "[".date("Y-m-d H:i:s")."]".$str;
$str .= PHP_EOL;
file_put_contents($path,$str,FILE_APPEND);
}
}
测试文件
<?php
include "Client.php";
$params = [
[
'to' => '2788828128@qq.com',
'subject' => '123',
'content' => '888',
'headers' => 'From: webmaster@example.com'
],
[
'to' => '2788828128@qq.com',
'subject' => '123',
'content' => '888',
'headers' => 'From: webmaster@example.com'
],
];
$msg = json_encode($params);
$client = new Client();
$client->send($msg);
echo "[".date("Y-m-d H:i:s")."]继续忙其他的".PHP_EOL;