ThinkPHP5.1 Workman如何調(diào)用寫好的主動推送函數(shù)?。ㄖ攸c(diǎn)是如何獲取worker對象)
$ChatDom = new Chat();
$ChatDom->ActivePrompt(【ThinkPHP5.1框架 這里填什么】,["mid" => 1327, "msg" => "注冊成功", "url" => ""]);
<?php
namespace app\api\controller;
use think\worker\Server;
use app\api\middleware\ApiAuth;
use app\api\model\Notifylog;
use app\api\model\Member;
// BaseClass
use Workerman\Worker;
use Workerman\Crontab\Crontab;
use Workerman\Connection\TcpConnection;
class Chat extends Server
{
// 消息格式 msg = ["code": 0=成功1=失敗2=離線, "msg": "", "data": []];
public $socket = 'websocket://0.0.0.0:2348';
public function onConnect(TcpConnection $connection){
// IP端口
$Client = "{$connection->getRemoteIp()}:{$connection->getRemotePort()}\r\n";
echo $Client;
}
public function onWebSocketConnect($connection, $http_buffer){
// 賬戶檢測
$HeaderArr = $this->parseHeaders($http_buffer);
$this->mark_($connection, $HeaderArr);
}
public function onMessage(TcpConnection $connection, $data){
}
public function onClose($connection){
// 設(shè)置賬戶消息的通信ID
Member::where(['notifyid' => $connection->id])->update(['notifyid' => -1]);
$connection->close($this->Magstruct(2, "斷開完畢"));
echo $connection->id."已斷開\n";
}
// 主動提醒, 如果有了信息消息。這個函數(shù)將 寫入消息數(shù)據(jù) 并調(diào)用通知客戶
public function ActivePrompt($connection, $Arr){
$query = new Notifylog();
$query->notifylog_mid = $Arr['mid'];
$query->notifylog_time = time();
$query->notifylog_url = $Arr['url'];
$query->notifylog_msg = $Arr['msg'];
if($query->save()){
$NotifyID = Member::where(["id" => $Arr['mid']])->value("notifyid");
$connection->worker->connection[$NotifyID]->send($this->Magstruct(0, "New Message"));
return;
}
print_r("ActivePrompt: MessAge WriteError");
}
//==========================================================================
// 連接并構(gòu)建
public function mark_($connection, $Data){
print_r($Data);
$Data['token'] = "e1cf1ab4313f1d2b7e03a0df3958f8ce";
$result = ApiAuth::checkToken($Data['token']);
if(empty($result['user_id'])) {
print_r("Invalid Token");
$connection->close($this->Magstruct(1, "認(rèn)證失敗"));
return false;
}
// 設(shè)置賬戶消息的通信ID
Member::where(['id' => $result['user_id']])->update(['notifyid' => $connection->id]);
$connection->send($this->Magstruct(0, "連接成功"));
return true;
}
public function Magstruct($code, $msg, $data = []){
return json_encode([
"code" => $code,
"msg" => $msg,
"datas" => $data
]);
}
// 解析字符串頭為數(shù)組
public function parseHeaders($http_buffer) {
$headers = array();
$requestHeaders = explode("\r\n", $http_buffer);
foreach ($requestHeaders as $header) {
if ($header !== '') {
$headerParts = explode(': ', $header, 2);
$headerKey = str_replace('-', '_', strtoupper($headerParts[0]));
$headerValue = isset($headerParts[1]) ? trim($headerParts[1]) : '';
$headers[$headerKey] = $headerValue;
}
}
return $headers;
}
}