Swoole

TCP面向对象

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
<?php
//服务端
class TCP
{
private $server = null;

public function __construct()
{
//创建Server对象,监听 127.0.0.1:9501 端口
$this->server = new Swoole\Server('127.0.0.1', 9501);

$this->server->set([
'worker_num' => 4,
'max_request' => 50,
]);

$this->server->on('Connect', [$this, "onConnect"]);
$this->server->on('Receive', [$this, "onReceive"]);
$this->server->on('Close', [$this, "onClose"]);
$this->server->start();
}

//监听连接进入事件
public function onConnect($server, $fd)
{
echo "客户端id:" . $fd . "连接.\n";
}
//监听数据接收事件
public function onReceive($server, $fd, $reactor_id, $data)
{
$server->send($fd, "发送的数据: {$data}");
}
//监听连接关闭事件
public function onClose($server, $fd){
echo "客户端id:" . $fd . "关闭.\n";
}


}


new TCP();

?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
//客服端
use Swoole\Coroutine\Client;
use function Swoole\Coroutine\run;

go(function () {
$client = new Client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
echo "connect failed. Error: {$client->errCode}\n";
}
fwrite(STDOUT,'请输入:');
$res=fgets(STDIN);
$client->send($res."\n");
echo $client->recv();
$client->close();
});
?>