当前位置:网站首页>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
边栏推荐
- 程序员坐牢了,会被安排去写代码吗?
- ##测试bug常用“Redmine”
- 移动Web实训-flex布局测试题1
- Go language learning notes - Gorm usage - database configuration, table addition | web framework gin (VII)
- pytorch模型
- Watermaker of the Flink core
- matlab plotyy 坐标轴设置,[转载]Matlab plotyy画双纵坐标图实例[通俗易懂]
- How to solve the data inconsistency between redis and MySQL?
- 全志V853芯片 如何在Tina V85x平台切换sensor?
- An idea plug-in that automatically generates unit tests, which improves the development efficiency by more than 70%!
猜你喜欢

Successful cases of rights protection of open source projects: successful rights protection of SPuG open source operation and maintenance platform

Centos6.5 php+mysql MySQL library not found

Implementation of fruit and vegetable mall management system based on SSM

Hubble数据库x某股份制商业银行:冠字号码管理系统升级,让每一张人民币都有 “身份证”

Align content attribute in flex layout

从pdb源码到frame帧对象

Mobile web training day-2

Mysq 8.0 launched histogram, which greatly improved the performance!

Watermaker of the Flink core

求职简历的书写技巧
随机推荐
New product experience: Alibaba cloud's new generation of local SSD instance I4 open beta
Solution to directory access of thinkphp6 multi-level controller
Vscode如何设置自动保存代码
matlab plotyy 坐标轴设置,[转载]Matlab plotyy画双纵坐标图实例[通俗易懂]
全志V853芯片 如何在Tina V85x平台切换sensor?
G1垃圾收集器中重要的配置参数及其默认值
词云的可视化设计教程
电驴怎么显示服务器列表,(转)如何更新电驴服务器列表(eMule Server List)
弹性盒子自动换行小Demo
How to solve the data inconsistency between redis and MySQL?
c语言中的类结构体-点号
Which company has a low rate for opening a securities account? How to open an account is the safest
Microservice stability guarantee
Centos7 - installing mysql5.7
Matlab plotyy coordinate axis setting, [reprint] example of MATLAB plotyy drawing double ordinate graph [easy to understand]
Mobile web training day-1
Deep understanding of Bayes theorem
认识启动函数,找到用户入口
How about stock online account opening and account opening process? Is it safe to open a mobile account?
How does Quanzhi v853 chip switch sensors on Tina v85x platform?