当前位置:网站首页>yii2连接websocket服务实现服务端主动推送消息给客户端
yii2连接websocket服务实现服务端主动推送消息给客户端
2022-06-28 13:16:00 【赫赫phper】
yii2编写swoole的websocket服务_赫赫phper的博客-CSDN博客
上一篇写的是websocket的服务,这一篇写写调用服务和web端调用,接收消息部分
1、调用websocket服务,主动推送消息的方法
<?php
namespace addons\ByThirdagency\common\services;
use addons\ByShop\common\exceptions\ShopException;
use common\helpers\EnvHelper;
use WebSocket\BadOpcodeException;
use WebSocket\Client;
use yii\base\Exception;
use yii\console\Controller;
class WebSocketSendService extends Controller
{
/**
* Param: 通过uid,推送消息给用户
* User: 赫赫
* Date: 2022/6/13
* @param $uid
* @param $price
* @return void
* @throws Exception
*/
public static function sendMsg($uid,$price)
{
if(!empty($uid)){
$uri = 'wss://' . EnvHelper::get('WEBSOCKET_URL');
$ws = new Client($uri);
try {
$data = [
'uid' =>$uid,
'type'=>'WEBSOCKET_URL',
'msg' =>"您好,收款:{$price}元"
];
$ws->send(json_encode($data,JSON_UNESCAPED_UNICODE));
return "发送成功\n";
usleep(100);
} catch (BadOpcodeException $e) {
throw new Exception($e->getMessage());
}
$ws->close();
}
}
}
2、在job中加入编写任务
<?php
namespace addons\ByThirdagency\common\jobs;
use addons\ByThirdagency\common\services\WebSocketSendService;
/**
* Param: 订单推送消息给用户
* Class SendMsgJob
* User: 赫赫
* Date: 2022/5/20
*/
class SendMsgJob extends \yii\base\BaseObject implements \yii\queue\JobInterface
{
public $uid;
public $price;
/**
* @inheritdoc
*/
public function execute($queue)
{
try {
$res = WebSocketSendService::sendMsg($this->uid,$this->price);
\Yii::$app->byfLog->channel('WebSocket')->info('推送消息给用户:'.$res);
}catch (\Exception $exception){
\Yii::$app->byfLog->channel('WebSocket')->error('推送消息给用户错误'.$exception->getFile() . ':' . $exception->getLine() . ':' . $exception->getMessage() . PHP_EOL);
}
}
}
3、推送消息加入异步队列:
<?php
namespace addons\ByThirdagency\console\controllers;
use addons\ByShop\common\exceptions\ShopException;
use addons\ByThirdagency\common\jobs\SendMsgJob;
use addons\ByThirdagency\common\services\WebSocketSendService;
use WebSocket\BadOpcodeException;
use yii\base\Exception;
use yii\console\Controller;
class WebSocketPushController extends Controller
{
/**
* Param: 通过uid,推送消息给用户
* User: 赫赫
* Date: 2022/6/13
* @param $uid
* @return void
* @throws Exception
*/
public function actionSendMsg($uid,$price)
{
try {
WebSocketSendService::sendMsg($uid,$price);
} catch (BadOpcodeException $e) {
throw new Exception($e->getMessage());
}
}
/**
* Param: 推送消息任务加入队列
* User: 赫赫
* Date: 2022/6/17
* @param $uid
* @param $price
* @return void
* @throws Exception
*/
public function actionSendMsgJob($uid,$price)
{
try {
//$this->uid,$this->price
\Yii::$app->queue->bind('websocket-job')->push(new SendMsgJob(['uid' => $uid,'price'=>$price]));
} catch (BadOpcodeException $e) {
throw new Exception($e->getMessage());
}
}
}
手动推送消息任务队列测试的命令:
php yii web-socket-push/send-msg-job 112402 4.9999
4、web端连接websocket服务,实现接收消息
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>websocket</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//获取url中的参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null) return unescape(r[2]); return null; //返回参数值
}
//使用方法, url中包含id这个参数
var uid = getUrlParam("uid")
if ("WebSocket" in window)
{
console.log('接收到的uid='+uid);
//创建webSocket对象
//var ws = new WebSocket("wss://test.***********.cn/wss?uid="+uid); //测试
//连接建立时触发
ws.onopen = function()
{
console.log('已经和幕后大佬建立连接');
}
//客户端接收服务端数据时触发
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log('收到大佬推送的消息:'+received_msg);
}
//连接关闭时触发
ws.onclose = function(evt)
{
console.log("连接已关闭...");
}
//连接关闭时触发
ws.onerror = function()
{
console.log("连接发生错误...");
}
}
else
{
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
function sendData() {
var msg = $("#msg").val();
ws.send(msg);
}
</script>
</head>
<body>
<input type="text" placeholder="请输入要发送的文字" id="msg">
<button onclick="sendData()">点击发送</button>
</body>
</html>
5、配置supervisor
[program:websocket-job]
command=php yii queue/listen websocket-job
directory=/www/data/test.*********.cn/
autorestart=true
startsecs=3
startretries=3
stdout_logfile=/var/log/supervisor/log/websocket-job.out.log
stderr_logfile=/var/log/supervisor/log/websocket-job.err.log
stdout_logfile_maxbytes=2MB
stderr_logfile_maxbytes=2MB
user=www
priority=999
numprocs=1
process_name=%(program_name)s_%(process_num)02d
边栏推荐
- Commonly used "redmine" for # test bug
- Fh511+tp4333 form an outdoor mobile power lighting camping lamp scheme.
- Centos7 - installing mysql5.7
- Arduino-ESP32闪存文件插件程序搭建和上传
- 完全背包 初学篇「建议收藏」
- Unit test ci/cd
- 电驴怎么显示服务器列表,(转)如何更新电驴服务器列表(eMule Server List)
- (原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
- Align content attribute in flex layout
- SHAREit实力出众,登陆全球 IAP 实力榜 Top7
猜你喜欢
认识启动函数,找到用户入口
Arduino-ESP32闪存文件插件程序搭建和上传
电脑无线网络不显示网络列表应该如何解决
Online JSON to plaintext tool
腾讯汤道生:面向数实融合新世界,开发者是最重要的“建筑师”
The counter attack story of Fu Jie, a young secondary school student: I spent 20 years from the second undergraduate to the ICLR outstanding Thesis Award
Vscode如何设置代码保存后自动格式化
SHAREit实力出众,登陆全球 IAP 实力榜 Top7
Oceanwide micro fh511 single chip microcomputer IC scheme small household appliances LED lighting MCU screen printing fh511
Vs2012 VC creates a new blank window application
随机推荐
中国数据库技术大会(DTCC)特邀科蓝SUNDB数据库专家精彩分享
go template with... End traversal usage
How to solve the data inconsistency between redis and MySQL?
Realization of a springboard machine
Centos7:切换mysql用户并登录mysql
895. 最长上升子序列
MySQL多表联合查询
Google Earth engine (GEE) - Global organic soil area of FAO (1992-2018)
Centos7 - installing mysql5.7
ShareIt has outstanding strength and landed in the top 7 of the global IAP strength list
plt. Usage of savefig() and save path
Fh511+tp4333 form an outdoor mobile power lighting camping lamp scheme.
Centos7: switch MySQL users and log in to MySQL
##测试bug常用“Redmine”
Professional English calendar questions
Hubble database x a joint-stock commercial bank: upgrade the number management system of Guanzi, so that every RMB has an "ID card"
Deep understanding of Bayes theorem
(原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
泛海微FH511单片机IC方案小家电LED照明MCU丝印FH511
Fastposter v2.8.4 release e-commerce poster generator