<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Lib\Timer;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('tcp://0.0.0.0:8686');
// 连接时的回调,表示完成了TCP三次握手
$worker->onConnect = function(TcpConnection $connection)
{
$connection->messageCount = 0;
};
// 客户端发送数据时的回调
$worker->onMessage = function(TcpConnection $connection, string $data)
{
echo '接收数据为:' . $data . PHP_EOL;
$limit = 100;
if(++$connection->messageCount > $limit)
{
// 使当前连接停止接收数据,该连接的onMessage回调将不会被触发。此方法对于上传流量控制非常有用
$connection->pauseRecv();
// 30秒后恢复接收数据
Timer::add(30, function($connection){
// 使当前连接继续接收数据。此方法与Connection::pauseRecv配合使用,对于上传流量控制非常有用
$connection->resumeRecv();
}, array($connection), false);
}
};
// 客户端关闭连接时的回调
$worker->onClose = function(TcpConnection $connection)
{
echo "connection{$connection->id} closed\n";
};
// 运行worker
Worker::runAll();