背景
近期公司要对接门禁设备,把服务器的人员信息推送到门禁设备里面。程序用的thinkphp5使用workerman组件。
1.安装wokerman
2.配置启动器
3.配置controller
4.启动websocket服务
5.客户端调用
服务器端
1.安装wokerman
安装方式官网推荐使用composer,在项目根目录下运行
composer require topthink/think-worker -vvv
如果不习惯用composer,那你就直接下载workerman后拷贝到vendor文件夹使用
2.配置启动器
在项目根目录下创建文件server.php
<?php
#!/usr/bin/env php
define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE','index/Worker');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
3.配置controller
这一步就是新建一个controller,我这里是直接在application文件夹push/controller中创建了的Worker.php
<?php
namespace app\push\controller;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\Hook;
use think\Request;
use think\Db;
class Worker extends Server
{
protected $socket = 'websocket://0.0.0.0:2346';
public $connectionArr = array();
/**
* 收到信息
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
global $worker;
$list = json_decode($data,true);
// var_dump($list);
// 给connection临时设置一个lastMessageTime属性,用来记录上次收到消息的时间
$connection->lastMessageTime = time();
switch ($list['method']) {
case "registerDevice":
if (!isset($connection->uid)) {
$time = time();
$connection->uid = $list['params']['DeviceId'];
echo "\r\n" . date('Y-m-d H:i:s') . "\r\n";
// echo "设备连接开始:" . "\r\n";
echo "连接设备的设备号:" . $list['params']['DeviceId'];
/* 保存uid到connection的映射,这样可以方便的通过uid查找connection,
* 实现针对特定uid推送数据
*/
$worker->uidConnections[$connection->uid] = $connection;
# 查询设备是否在系统
$device = Db::table('moredian_device')
->where('deviceSn', $list['params']['DeviceId'])
->find();
if($device){
# 发送返回数据
$Timestamp = ['Timestamp' => time()];
$arr = array('method'=>'registerDevice','params' =>$Timestamp, 'result'=>0,'errMsg'=>'设备已经注册!','req_id'=>$list['req_id']);
$connection->send(json_encode($arr));
}else{
$device_data = [
'deviceId' => $list['req_id'],
'deviceName' => $list['params']['ProdName'],
'deviceSn' => $list['params']['DeviceId'],
'controlDoorTime' => $list['params']['DeviceVerDate'],
'deviceType' => $list['params']['ProdType'],
];
Db::table('moredian_device')->insert( $device_data );
# 发送返回数据
$Timestamp = ['Timestamp' => time()];
$arr = array('method'=>'registerDevice','params' =>$Timestamp, 'result'=>0,'errMsg'=>'Success','req_id'=>$list['req_id']);
$connection->send(json_encode($arr));
}
}
break;
case "heartBeat":
# 发送返回数据
// $Timestamp = ['Timestamp' => time()];
$device_data = [
'status' =>1
];
Db::table('moredian_device')->where('deviceSn',$list['params']['DeviceId'])->upda