一、TCP服务
TCP服务端
我们看Swoole官方文档入门指引->快速起步->创建TCP服务器,把文档的示例代码跑一次,看下效果:
server.php
<?php
//创建Server对象,监听 127.0.0.1:9501端口
$serv = new Swoole\Server("127.0.0.1", 9501);
// 设置自定义参数
// @doc https://wiki.swoole.com/wiki/page/13.html
$serv->set([
'worker_num' => 8, // worker 进程数为cpu 1-4倍
'max_request' => 10000,
]);
//监听连接进入事件
/**
* $fd 客户端连接的唯一标识
* $reactor_id 线程ID
*/
$serv->on('Connect', function ($serv, $fd, $reactorId) {
echo "Client: {$reactorId}-{$fd}-Connect.\n";
});
//监听数据接收事件
$serv->on('Receive', function ($serv, $fd, $reactorId, $data) {
$serv->send($fd, "Server: {$reactorId} - {$fd} ".$data);
});
//监听连接关闭事件
$serv->on('Close', function ($serv, $fd) {
echo "Client: Close.\n";
});
//启动服务器
$serv->start();
我们先开启服务,然后再通过 telnet
命令分别开启两个窗口连接该服务
root@5ee6bfcc1310:/work/study/code/swoole/demo/server# php server.php
Client: 0-1-Connect.
Client: 1-2-Connect.
0号客户端:
root@5ee6bfcc1310:/# telnet 127.0.0.1 9501
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hello
Server: 0 - 1 hello
1号客户端:
root@5ee6bfcc1310:/# telnet 127.0.0.1 9501
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hello
Server: 1 - 2 hello
TCP客户端
tcp_client.php
<?php
// 该文件模拟 telnet 127.0.0.1 9501 命令进行请求服务端
// 连接 Swoole tcp 服务
$client = new Swoole\Client(SWOOLE_SOCK_TCP);
if(!$client->connect("127.0.0.1", 9501)){
echo 'Connect error';
exit;
}
// php cli常量
fwrite(STDOUT, "请输入消息");
$msg = trim(fgets(STDIN));
// 发送消息给 tcp server 服务器
$client->send($msg);
// 接收来自server的数据
$res = $client->recv();
echo $res;
执行该脚本:
php tcp_client.php
打印:
root@5ee6bfcc1310:~# /work/study/soft/php/bin/php /work/study/code/swoole/demo/client/tcp_client.php
请输入消息3
Server: 0 - 3 3