### 安装 `composer require workerman/workerman` ~~~ "workerman/workerman": "^4.0" ~~~ ### 代码构建 ~~~ <?php /** * Name * Created by WML * Created on 2022/3/12 */ use Workerman\Timer; use Workerman\Worker; use Workerman\Connection\TcpConnection; require_once __DIR__ . '/vendor/autoload.php'; // 心跳间隔55秒 define('HEARTBEAT_TIME', 55); // 注意:这里与上个例子不同,使用的是websocket协议 $ws_worker = new Worker("websocket://0.0.0.0:12124"); // 启动4个进程对外提供服务 $ws_worker->count = 4; //当客户端连接上来的时候 $ws_worker->onConnect = function (TcpConnection $connection) { $connection->send("连接成功,有什么可以帮助你的吗?"); }; // 当收到客户端发来的数据后返回hello $data给客户端 $ws_worker->onMessage = function(TcpConnection $connection, $data) { $connection->lastMessageTime = time(); // 向客户端发送hello $data $connection->send('hello ' . $data); }; $ws_worker->onClose = function (TcpConnection $connection) { var_dump('连接关闭'); }; // 进程启动后设置一个每10秒运行一次的定时器 $ws_worker->onWorkerStart = function($worker) { Timer::add(10, function()use($worker){ $time_now = time(); foreach($worker->connections as $connection) { // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间 if (empty($connection->lastMessageTime)) { $connection->lastMessageTime = $time_now; continue; } // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接 if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) { $connection->close(); } } }); }; // 运行worker Worker::runAll(); ~~~ ### 执行