这不是教程,只是在实际项目中应用了Workerman,以此记录
public function socket()
{
//命令行永久运行
set_time_limit(0);
//指定日志位置
\Workerman\Worker::$logFile=DIR_ROOT.'run/log/workerman/workerman.log';
//创建一个Worker进行
$worker = new \Workerman\Worker();
//进程数设置为8
$worker->count=8;
//启动时要执行的代码
$worker->onWorkerStart = function (\Workerman\Worker $task) {
//创建一个连接 (我们作为 客户端)
$connection = new AsyncTcpConnection('tcp://' . configMust('api', '床垫域名') . ':' . configMust('api', '床垫socket端口'));
//连接成功时执行
$connection->onConnect = function (AsyncTcpConnection $connection) {
echo microtime(true) . ' connect success' . PHP_EOL;
//获取Token
$token = MMattress::getToken();
//发送命令
$str = "AUTH_CHANNEL," . $token['appId'] . "\n";
$connection->send($str);
};
//接收到数据时执行
$connection->onMessage = function (AsyncTcpConnection $connection, string $msg) {
//echo microtime(true) . ' Read ' . $msg . PHP_EOL;
if (!$msg) {
echo microtime(true) . ' Read Null' . PHP_EOL;
return;
}
//可能是多行
$msgs = explode("\n", $msg);
//只显示处理了几条数据
echo microtime(true) . ' READ:' . count($msgs) . PHP_EOL;
//逐条数据处理
foreach ($msgs as $m) {
MMattressData::updateJson($m);
}
};
$connection->onClose = function (AsyncTcpConnection $connection) {
echo microtime(true) . ' Close' . PHP_EOL;
$connection->connect();
};
$connection->onError = function (AsyncTcpConnection $connection, string $code, string $msg) {
echo microtime(true) . ' Error: ' . $code . ' ' . $msg . PHP_EOL;
};
$connection->connect();
};
//启动全部Worker
\Workerman\Worker::runAll();
}
---------------------
作者:蓝冰大侠
来源:CSDN
原文:https://blog.csdn.net/bluehire/article/details/84823213
版权声明:本文为博主原创文章,转载请附上博文链接!