1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
class Server
{
private $server;
public function __construct()
{
$this->server = new \swoole_server("0.0.0.0", 9501);
$this->server->set([
'worker_num' => 2,
'daemonize' => true,
'task_worker_num' => 2 # task 进程数
]);
$this->server->on('Start', [$this, 'onStart']);
$this->server->on('Connect', [$this, 'onConnect']);
$this->server->on('Receive', [$this, 'onReceive']);
$this->server->on('Task', [$this, 'onTask']);
$this->server->on('Finish', [$this, 'onFinish']);
$this->server->on('Close', [$this, 'onClose']);
$this->server->start();
}
// 主进程启动时回调函数
public function onStart(\swoole_server $server)
{
echo "开始、n";
}
// 建立连接时回调函数
public function onConnect(\swoole_server $server, $fd, $from_id)
{
echo "连接上了、n";
}
public function onReceive(\swoole_server $server, $fd, $from_id, $data)
{
// 投递异步任务
$task_id = $server->task($data);
// echo "Dispath AsyncTask: id={$task_id}\n";
// 将受到的客户端消息再返回给客户端
$server->send($fd, "Message form Server: {$data}, task_id: {$task_id}");
}
// 异步任务处理函数
public function onTask(\swoole_server $server, $task_id, $from_id, $data)
{
echo " \n {$task_id}, start task \n";
sleep(5);
echo " \n {$task_id}, end task \n";
$server->finish('t');
}
public function onFinish(\swoole_server $server, $task_id, $data)
{
echo "finish";
}
// 关闭连时回调函数
public function onClose(\swoole_server $server, $fd, $from_id)
{
echo "close \n";
}
}
$server = new Server();
|