swoole-tcp客户端服务器

PHP技术
429
0
0
2022-11-02
标签   Swoole

服务器代码 tcp.php

<?php

//创建Server对象,监听 127.0.0.1:9501 端口
$server = new swoole_server('127.0.0.1', 9501);

$server->set([
    'worker_num' => 4
]);
//监听连接进入事件
$server->on('Connect', function ($server, $fd) {
    echo "Client: Connect.\n";
});

//监听数据接收事件
$server->on('Receive', function ($server, $fd, $reactor_id, $data) {
    $server->send(1, "Server:$fd- {$data}");
});

//监听连接关闭事件
$server->on('Close', function ($server, $fd) {
    echo "Client: Close.\n";
});

//启动服务器
$server->start();

客户端代码 tcp_client.php

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP);

if(!$client->connect("127.0.0.1", 9501)) {
  echo "链接失败";
}
//php内置cli常量
fwrite(STDOUT, "请输入消息:");
$msg = trim(fgets(STDIN));

//发送消息给tcp server服务器
$client->send($msg);

//接受来自server的消息
$result = $client->recv();
echo $result;

客户端和服务器运行

php tcp_client.php
php tcp.php

自行测试

查看跑起几个worker

在终端输入:

ps aft | grep tcp.php
效果图: