workerman使用记录
composer安装workerman
composer require workerman/workerman
项目根目录创建worker.php
<?php // worker.php use Workerman\Worker; use GatewayWorker\Gateway; use GatewayWorker\BusinessWorker; use GatewayWorker\Register; // Autoload require_once __DIR__ . '/vendor/autoload.php'; // 初始化BusinessWorker $worker = new BusinessWorker(); $worker->name = 'YourBusinessWorkerName'; $worker->count = 4; $worker->registerAddress = '127.0.0.1:1238'; $worker->eventHandler = '\app\common\lib\TcpHandler'; // 初始化GatewayWorker $gateway = new Gateway("tcp://0.0.0.0:8282"); $gateway->name = 'YourGatewayName'; $gateway->count = 4; $gateway->lanIp = '127.0.0.1'; $gateway->startPort = 2900; $gateway->registerAddress = '127.0.0.1:1238'; // register 必须是text协议 $register = new Register('text://0.0.0.0:1238'); Worker::runAll();
\app\common\lib\TcpHandler如下:
<?php namespace app\common\lib; use GatewayWorker\Lib\Gateway; use Workerman\Connection\ConnectionInterface; class TcpHandler { public static function onConnect($clientID) { // 客户端连接时的处理 echo $clientID . " has connected !\r\n"; } public static function onMessage($clientID, $data) { // 处理接收到的消息 // 这里可以调用ThinkPHP的模型、服务等进行业务处理 // 处理完成后,可以使用Gateway::sendToClient()发送消息给客户端 echo strtolower(bin2hex($data)); echo "\r\n"; } public static function onClose($clientID) { // 客户端断开连接时的处理 echo $clientID . " has logout.\r\n"; } }
设备在首次通电后,上报“注册”指令,且携带设备编号,此时使用bindUid方法,将客户端ID和设备编号绑定。
之后的业务逻辑中只需要使用sendToUid方法向设备编号对应的客户端ID发送数据即可。
.