企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[danger] tcp: * **用途**:门禁卡、rcp远程通讯、发送短信、即时聊天。 * **客户端代码** ~~~ <?php // 实例化客户端 $client = new Swoole\Client(SWOOLE_SOCK_TCP); // 建立连接 if (!$client->connect('127.0.0.1', 9503, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } // 发送 $client->send("hello world\n"); // 获取服务端数据 echo $client->recv(); // 关闭 $client->close(); ~~~ * **服务端代码** ~~~ <?php $server = new Swoole\Server("0.0.0.0", 9503); // 连接 $server->on('connect', function ($server, $fd){ echo "connection open: {$fd}\n"; }); // 消息 $server->on('receive', function ($server, $fd, $reactor_id, $data) { $server->send($fd, "Swoole: {$data}"); $server->close($fd); }); // 关闭 $server->on('close', function ($server, $fd) { echo "connection close: {$fd}\n"; }); // 打开 $server->start(); ~~~ * **执行效果** 1. 开启服务监听 ![](https://img.kancloud.cn/22/c4/22c496243943d6735928556593cc0d5c_635x288.png) 2. 客户端运行 2.1 cli 方式运行 ![](https://img.kancloud.cn/f6/7a/f67a89c7a47b72986d9c9d7b14411fa3_562x291.png) 2.2 浏览器运行 ![](https://img.kancloud.cn/7a/ca/7aca257075edab38e591949f23366fb1_841x341.png) >[danger] udp: * 用途:直播 * **客户端代码** ~~~ <?php // 实例化客户端 $client = new Swoole\Client(SWOOLE_SOCK_UDP); // 建立连接 if (!$client->connect('127.0.0.1', 9502, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } // 发送 $client->send("hello world\n"); // 获取服务端数据 echo $client->recv(); // 关闭 $client->close(); ~~~ * **服务端代码** ~~~ <?php $server = new Swoole\Server("0.0.0.0", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); $server->on('Packet', function ($server, $data, $clientInfo) { $server->sendTo($clientInfo['address'], $clientInfo['port'], "Server ".$data); var_dump($clientInfo); }); $server->start(); ~~~ * **执行效果** 1. 开启服务监听 ![](https://img.kancloud.cn/cf/9f/cf9fdf007a45505cf33c61188caa1220_583x282.png) 2. 客户端运行 ![](https://img.kancloud.cn/a9/36/a936c2b5551e4a642fbdd83c566d0acc_510x283.png) >[danger] 定时器: * **旧版官方代码** ~~~ <?php // 每隔2000ms触发一次 swoole_timer_tick(2000, function ($timer_id) { echo "tick-2000ms\n"; // 清除此定时器 // swoole_timer_clear($timer_id); }); // 3000ms后执行此函数 swoole_timer_after(3000, function () { echo "after 3000ms.\n"; }); ~~~ * **执行效果** ![](https://img.kancloud.cn/7d/5f/7d5f883fb21ab95db67318742e8a04fb_351x122.png)