🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 安装 ## thinkphp5.1中一定要带上=1.*不然会报错 ``` composer require workerman/channel=1.* ``` ## 错误解决: ``` 一般在报版本错误的时候 就加上 = 版本号 * 就可以 ``` ![](https://img.kancloud.cn/8d/f7/8df7f71e203018a9146ce5219524e928_3513x499.png) # channel启动服务器与客户端 ~~~ <?php namespace app\http; use Channel\Client; use think\worker\Server; use Channel\Server as Channel_Server; class On extends Server { protected $socket = 'websocket://0.0.0.0:7777'; protected $option=['name'=>"学习",'count'=>2]; //修改名称,启动多少进程等配置 //启动成功的回调 public function onConnect($connection){ //连接成功后发送给客户端 worker_id 和connection_id用户ID $connection->send('connection_id='.$connection->id.'worker_id='.$this->worker->id); echo $connection->getRemoteIp(); } //设置Worker子进程启动时的回调函数,每个子进程启动时都会执行。 public function onWorkerStart($worker){ Client::connect('127.0.0.1',8881); //单个用户订阅事件 Client::on($worker->id,function ($data)use($worker){ //没有用户ID的返回掉 if(!isset($data['connection_id'])){ return ; } //获得用户ID的对象然后发送消息 $connection=$worker->connections[$data['connection_id']]; //如果得知connection的编号为$id,可以很方便的通过$worker->connections[$id]获得对应的connection对象,从而操作对应的socket连接,例如通过$worker->connections[$id]->send('...') 发送数据。 $connection->send($data['content']);//向对应的用户编号发布消息 }); //所有网站链接用户的订阅事件 Client::on('broadcast',function ($data)use($worker){ foreach ($worker->connections as $conn){ $conn->send($data['content']); } }); } } //channel服务器端开启 new Channel_Server('0.0.0.0',8881); ~~~ ## 写一个HTTP端发送数据 ~~~ <?php namespace app\http; use Channel\Client; use think\worker\Server; class Publish extends Server { protected $socket = 'http://0.0.0.0:9999'; protected $option = ['name' => "http发送"]; //修改名称,启动多少进程等配置 public function onWorkerStart($worker) { Client::connect('127.0.0.1', 8881); } public function onMessage($connection, $data) { $connection->send('oook'); // http://111.67.202.126:9999?content=login success&connection_id=2&worker_id=0 //单个用户发布 if(!isset($_GET['content'])){ return ; } if (isset($_GET['worker_id']) && isset($_GET['connection_id'])) { $data = ['connection_id' => $_GET['connection_id'], 'content' => $_GET['content']]; Client::publish($_GET['worker_id'], $data); } else { Client::publish('broadcast',['content' => $_GET['content']]); } } } ~~~ # 定时器端,定时发送 ~~~ <?php namespace app\http; use Workerman\Lib\Timer as T; use think\worker\Server; class Timer extends Server { protected $option=['name'=>"定时器"]; //修改名称,启动多少进程等配置 public function onWorkerStart(){ $time_interval = 5; T::add($time_interval, function() { $u='http://111.67.202.126:9999?content=虎赢'; //网站 $ch=curl_init(); //初始化curl会话返回curl句柄(资源) curl_setopt($ch,CURLOPT_URL,$u); //设置获取地址变量 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); //以字符串形式返回 $ma=curl_exec($ch); curl_close($ch); //关闭句柄 echo $ma."\n"; }); } } ~~~ ## 启动起来效果 ![](https://img.kancloud.cn/37/98/379878748fedff1451fd69185390b5af_2917x555.png)