续安装好composer和workerman之后;TP5运行workerman的操作

时间:2022-12-01 03:57:28

TP5想要实现时时通讯:首先先安装好composer和workerman,我之前有写一篇安装的方法,在cmd里面安装;tp5手册上面有写cmd命令的代码;接下来是安装好后如何运行的;

首先在项目中建立一个模块,这边就叫socket模块吧,里面有控制器,index.php;在此之前在config配置文件里面将

'default_module'         => 'socket',默认加载的模块为socket;
然后,在控制器里面写代码:
<?php
namespace app\socket\controller;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\Db;
class Index extends Server
{
protected $socket = 'websocket://localhost:2346'; /**
* 收到信息
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
$connection->send('我收到你的信息了');
} /**
* 当连接建立时触发的回调函数
* @param $connection
*/
public function onConnect($connection)
{ } /**
* 当连接断开时触发的回调函数
* @param $connection
*/
public function onClose($connection)
{ } /**
* 当客户端的连接上发生错误时触发
* @param $connection
* @param $code
* @param $msg
*/
public function onError($connection, $code, $msg)
{
echo "error $code $msg\n";
} /**
* 每个进程启动
* @param $worker
*/
public function onWorkerStart($worker)
{ Timer::add(5, function()use($worker){ $online_people_count = Db::name('session')->count();
$deal_order_count = Db::name('order')->where('order_status',1)->count();
$sale_server_count = Db::name('service')->where('service_status',1)->count();
//echo "".$online_people_count.'--------'.$deal_order_count.'----------'.$sale_server_count; $z="{$online_people_count},{$deal_order_count},{$sale_server_count}"; foreach($worker->connections as $connection) {
$connection->send($z);
}
});
}
}
这边的代码主要还是看,onWorkerStart这个方法,这个方法,获取数据库的值之后,传给需要接收那个数据的
视图模块,就是页面需要哪里显示那个数据,就是通过这里来发送的数据,这里是每五秒访问一次数据库
有了这些之后在,视图模块代码里面接收数据的代码:
//监听消息
// 连接服务端
try{
ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
console.log('连接成功'); };
ws.onmessage = function(e) {
var result = e.data.split(',');
if(result.length==3){
$("#on_people_sum").html(result[0]);
$("#menu23").html(result[1]);
$("#menu28").html(result[2]);
} }; }catch(err){ }
这样上面的result[0]...;就是数据库中获取的数据,只要数据有改变这个值就会改变;
最后在cmd里面运行D:\phpStudy\WWW\bestonapp\public>php index.php
----------------------- WORKERMAN -----------------------------
Workerman version:3.3.90          PHP version:5.4.45
------------------------ WORKERS -------------------------------
worker        listen                      processes status
none          websocket://localhost:2346   4        [OK]
----------------------------------------------------------------
Press Ctrl-C to quit. Start success.这是最终结果;这样就能时时获取数据库的数据了;