使用以下代碼可以更改設置。
後端代碼
push.php
<?php
use?Workerman\Worker;
require_once?'./Workerman/Autoloader.php';
$worker?=?new?Worker('websocket://0.0.0.0:1234');
//?這裏進程數必須設置為1
$worker->count?=?1;
//?worker進程啟動後建立壹個內部通訊端口
$worker->onWorkerStart?=?function($worker)
{
//?開啟壹個內部端口,方便內部系統推送數據,Text協議格式?文本+換行符$inner_text_worker?=?new?Worker('Text://0.0.0.0:5678');
$inner_text_worker->onMessage?=?function($connection,?$buffer)
{
global?$worker;
//?$data數組格式,裏面有uid,表示向那個uid的頁面推送數據
$data?=?json_decode($buffer,?true);
$uid?=?$data['uid'];
//?通過workerman,向uid的頁面推送數據
$ret?=?sendMessageByUid($uid,?$buffer);
//?返回推送結果
$connection->send($ret'ok'?:?'fail');
};
$inner_text_worker->listen();
};
//?新增加壹個屬性,用來保存uid到connection的映射
$worker->uidConnections?=?array();
//?當有客戶端發來消息時執行的回調函數$worker->onMessage?=?function($connection,?$data)use($worker)
{
//?判斷當前客戶端是否已經驗證,既是否設置了uid
if(!isset($connection->uid))
{
//?沒驗證的話把第壹個包當做uid(這裏為了方便演示,沒做真正的驗證)
$connection->uid?=?$data;
/*?保存uid到connection的映射,這樣可以方便的通過uid查找connection,
*?實現針對特定uid推送數據
*/
$worker->uidConnections[$connection->uid]?=?$connection;
return;
}
};
//?當有客戶端連接斷開時
$worker->onClose?=?function($connection)use($worker)
{
global?$worker;
if(isset($connection->uid))
{
//?連接斷開時刪除映射
unset($worker->uidConnections[$connection->uid]);
}
};
//?向所有驗證的用戶推送數據
function?broadcast($message)
{
global?$worker;
foreach($worker->uidConnections?as?$connection)
{
$connection->send($message);
}
}
//?針對uid推送數據
function?sendMessageByUid($uid,?$message)
{
global?$worker;
if(isset($worker->uidConnections[$uid]))
{
$connection?=?$worker->uidConnections[$uid];
$connection->send($message);
return?true;
}
return?false;
}
//?運行所有的worker(其實當前只定義了壹個)
Worker::runAll();
啟動後端服務
php?push.php?start?-d
前端接收推送的js代碼
var?ws?=?new?WebSocket('ws://127.0.0.1:1234');
ws.onopen?=?function(){
var?uid?=?'uid1';
ws.send(uid);
};
ws.onmessage?=?function(e){
alert(e.data);
};後端推送消息的代碼
//?建立socket連接到內部推送端口
$client?=?stream_socket_client('tcp://127.0.0.1:5678',?$errno,?$errmsg,?1,?STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT);
//?推送的數據,包含uid字段,表示是給這個uid推送
$data?=?array('uid'=>'uid1',?'percent'=>'88%');
//?發送數據,註意5678端口是Text協議的端口,Text協議需要在數據末尾加上換行符
fwrite($client,?json_encode($data)."\n");
//?讀取推送結果
echo?fread($client,?8192);這裏的uid不壹定是用戶的id,也可以理解為任務id即 taskid