Swoole TCP&UDP服务端

1.创建 server.php

<?php
//创建Server对象,监听 127.0.0.1:9501 端口
$server = new Swoole\Server('127.0.0.1', 1111);

$server->set([
    'worker_num'=>8, //worker进程数,cpu 1-4
    'max_request'=>10000,
]);

//监听连接进入事件
/**
 * $fd 客户端连接唯一标识
 * $reactor_id 线程ID
 */
$server->on('Connect', function ($server, $fd,$reactor_id) {
    echo "Client: fd:{$fd}-reactor_id:{$reactor_id}-Connect.\n";
});

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

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

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

2.客户端测试

命令:telnet -4 localhost 1111

服务端返回数据:Client: fd:1-reactor_id:0-Connect.

客户端返回数据:Server: reactor_id:0-fd:1-data:1

3.查看看启进程数

ps aft | grep server.php

 

【UDP服务端】

1.创建 server.php

<?php
//创建Server对象,监听 127.0.0.1:9501 端口
$server = new Swoole\Server('0.0.0.0', 2222, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);

//监听数据接收事件
$server->on('Packet', function ($server, $data, $clientInfo) {
    var_dump($clientInfo);
    $server->sendto($clientInfo['address'], $clientInfo['port'], "Server:{$data}");
});

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

 

posted @ 2022-06-24 17:11  快乐的在一起  阅读(34)  评论(0编辑  收藏  举报