首页
仓库
文档
nginx手册
Docker手册
workerman
Flask
PHP
python
RabbitMQ
其他
Linux
占位1
占位2
目录
###TCP 服务端 <?php use Workerman\Worker; use Workerman\Connection\TcpConnection; require_once __DIR__ . '/vendor/autoload.php'; // 注意:这里与上个例子不同,使用的是websocket协议 $worker = new Worker("tcp://0.0.0.0:22120"); // 启动4个进程对外提供服务 $worker->count = 2; $worker->onConnect = function(TcpConnection $connection) use($worker) { echo "new user : " .$worker->id.'-'. $connection->id.'-'. $connection->getRemoteIp() . "\n"; }; // 当收到客户端发来的数据后返回hello $data给客户端 $worker->onMessage = function(TcpConnection $connection, $json) use ($worker) { echo "from :".$worker->id.'-'.$connection->id."-data:".$json."\n"; print_r($data); $connection->send(['code'=>0,'msg'=>'登陆成功']); }; $worker->onClose = function(TcpConnection $connection)use($worker) { echo "connection closed".$worker->id.'-'. $connection->id."\n"; }; $worker->onError = function(TcpConnection $connection, $code, $msg) { echo "error $code $msg\n"; }; // 运行worker Worker::runAll(); ###TCP客户端 ``` <? use Workerman\Worker; use Workerman\Connection\AsyncTcpConnection; use Workerman\Connection\TcpConnection; use Workerman\Timer; require_once __DIR__ . '/vendor/autoload.php'; $task = new Worker("tcp://0.0.0.0:32288"); //设置当前Worker实例的名称,方便运行status命令时识别进程。不设置时默认为none。 $task->name = 'name'; // 启动1个进程对外提供服务 $task->count = 1; $task->onWorkerStart = function($task) { global $db; $db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'cloud', '123123', 'cloud'); Timer::add(10, function() use($db,$task) { echo "开始同步计划任务!\n"; $time=time(); $ls = $db->row("SELECT * FROM `ms_ct1zt` WHERE ( $time>(unix_timestamp(uptime)+(jiange*60)) or uptime is null ) and zt=1 order by id desc limit 1 "); if($ls){ echo '开始发送报文'."\n"; $connection_to_ct = new AsyncTcpConnection('tcp://123.123.123.123:123123'); // 当连接建立成功时,发送请求数据 $connection_to_ct->onConnect = function(AsyncTcpConnection $connection_to_ct) use($db,$st,$rid,$sbid) { $st=hex2bin($st); $connection_to_ct->send($st); $sj=date('Y-m-d H:i:s'); $db->query("UPDATE `ms_ct1zt` SET `uptime` = '$sj' WHERE id='$rid'"); }; $connection_to_ct->onClose = function(AsyncTcpConnection $connection_to_ct) { echo "connection closed\n"; }; $connection_to_ct->onError = function(AsyncTcpConnection $connection_to_ct, $code, $msg) { echo "Error code:$code msg:$msg\n"; }; $connection_to_ct->connect(); } }); }; // 运行worker Worker::runAll(); ```