小白一個(gè),剛剛安裝了workerman,前端推送數(shù)據(jù)沒有問題,現(xiàn)在想tp的后端推送消息給指定用戶,怎么推送呢?有沒有源碼參考一下,最好可以是tp的
是不是要安裝channel組件呢,是的話怎么用呢
這個(gè)官網(wǎng)有呀,就是tp推給workerman 然后workerman websocket推送給前端,這個(gè)代碼你看看手冊(cè)啥的很好寫呀
worker代碼:
<?php
namespace app\push\controller;
use think\worker\Server;
class Worker extends Server
{
protected $socket = 'websocket://0.0.0.0:2346';
protected $uidConnections = [];
protected $HEARTBEAT_TIME = '300';//心跳
/**
* 收到信息
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
$data = json_decode($data,false);
//給connection臨時(shí)設(shè)置一個(gè)lastMessageTime屬性,用來記錄上次收到消息的時(shí)間
$connection->lastMessageTime = time();
switch($data->type){
case 'login':
//首次進(jìn)入
$this->uidConnections[$data->uid] = $connection;//保存身份
$this->push_news($data->uid,$data->host);
break;
case 'pushNews':
//消息推送
$this->push_news($data->uid,$data->host,$data->msg);
break;
}
}
/**
* 當(dāng)連接建立時(shí)觸發(fā)的回調(diào)函數(shù)
* @param $connection
*/
public function onConnect($connection)
{
}
/**
* 當(dāng)連接斷開時(shí)觸發(fā)的回調(diào)函數(shù)
* 連接斷開銷毀連接對(duì)象節(jié)約內(nèi)存空間
* @param $connection
*/
public function onClose($connection)
{
/* unset($this->uidConnections[$connection->uid]);
unset($connection); */
}
/**
* 當(dāng)客戶端的連接上發(fā)生錯(cuò)誤時(shí)觸發(fā)
* @param $connection
* @param $code
* @param $msg
*/
public function onError($connection, $code, $msg)
{
echo "error $code $msg\n";
}
/**
* 每個(gè)進(jìn)程啟動(dòng)
* @param $worker
*/
public function onWorkerStart($worker)
{
// 開啟一個(gè)內(nèi)部端口,方便內(nèi)部系統(tǒng)推送數(shù)據(jù),Text協(xié)議格式 文本+換行符
$inner_text_worker = new \Workerman\Worker('Text://0.0.0.0:6890');
$inner_text_worker->onMessage = function ($connection, $buffer){
$buffer = json_decode($buffer,false);
$res = '';
if($buffer->type == 'pushNews')
{
//$connection->send(json_encode($this->uidConnections));
//消息推送
$res = $this->push_news($buffer->uid,$buffer->host,$buffer->msg);
}
$connection->send($res ? 'ok' : 'fail');
};
$inner_text_worker->listen();
}
//消息推送
public function push_news($uid,$host,$msg='')
{
if(isset($this->uidConnections[$uid])){
// 獲取之前用戶的鏈接
$conn = $this->uidConnections[$uid];
$conn->send(json_encode(['type'=>'push','num'=>'消息數(shù)','msg'=>$msg]));
return true;
}
return false;
}
}
php推送:
$client = stream_socket_client('tcp://127.0.0.1:6890', $errno, $errmsg, 1);
$data = ['type'=>'pushNews','host'=>'host','uid'=>'user-1','msg'=>'消息內(nèi)容'];
//發(fā)送數(shù)據(jù),Text協(xié)議需要在數(shù)據(jù)末尾加上換行符
fwrite($client, json_encode($data)."\n");
//讀取推送結(jié)果
echo fread($client, 8192);