当前位置:网站首页>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
边栏推荐
- Electronic components distribution 1billion Club [easy to understand]
- SHAREit实力出众,登陆全球 IAP 实力榜 Top7
- How to handle the safest account opening when downloading the mobile app of Huatai Securities
- Online JSON to plaintext tool
- 新品体验:阿里云新一代本地SSD实例i4开放公测
- How about stock online account opening and account opening process? Is it safe to open a mobile account?
- Writing skills of resume
- 一文搞懂leveldb写操作
- Vs2012 VC creates a new blank window application
- 我呕血收集融合了来自各路经典shell书籍的脚本教学,作为小白的你快点来吧
猜你喜欢

一文搞懂leveldb写操作

5A同步整流芯片 20V转12V2A/5V4.5A大电流 24W大功率同步整流芯片 大电流降压IC FS2462

Implementation of fruit and vegetable mall management system based on SSM

开源项目维权成功案例: Spug 开源运维平台成功维权

Mysql database literacy, do you really know what a database is

MySQL multi table joint query

Setup and upload of arduino-esp32 flash file plug-in program

mysql数据库扫盲,你真的知道什么是数据库嘛

Fs7022 scheme series fs4059a dual two lithium battery series charging IC and protection IC

Arduino-ESP32闪存文件插件程序搭建和上传
随机推荐
Elastic box auto wrap demo
China Database Technology Conference (DTCC) specially invited experts from Kelan sundb database to share
Matlab plotyy coordinate axis setting, [reprint] example of MATLAB plotyy drawing double ordinate graph [easy to understand]
Scratch travel photo album Electronic Society graphical programming scratch grade examination level 1 true questions and answers analysis June 2022
Implementation of fruit and vegetable mall management system based on SSM
PHP obtains the beginning and end time of the month according to the month and year
Resume template Baidu online disk
我呕血收集融合了来自各路经典shell书籍的脚本教学,作为小白的你快点来吧
电驴怎么显示服务器列表,(转)如何更新电驴服务器列表(eMule Server List)
pytorch模型调参、训练相关内容
电脑无线网络不显示网络列表应该如何解决
The English translation of heartless sword Zhu Xi's two impressions of reading
移动Web实训DAY-2
中二青年付杰的逆袭故事:从二本生到 ICLR 杰出论文奖,我用了20年
Copy 10 for one article! The top conference papers published in South Korea were exposed to be plagiarized, and the first author was "original sin"?
flutter 系列之:flutter 中常用的 GridView layout 详解
You must configure either the server or JDBC driver (via the ‘serverTimezone‘ configuration property
无心剑英译朱熹《观书有感二首·其一》
中国数据库技术大会(DTCC)特邀科蓝SUNDB数据库专家精彩分享
RK3399平台开发系列讲解(使用篇)Pinctrl子系统的介绍 - 视频介绍