当前位置:网站首页>Yii2 connects to websocket service to realize that the server actively pushes messages to the client
Yii2 connects to websocket service to realize that the server actively pushes messages to the client
2022-06-28 13:28:00 【Hehe PHPer】
yii2 To write swoole Of websocket service _ Hehe phper The blog of -CSDN Blog
The last one was about websocket Service for , This article describes calling services and web End calls , Receive message part
1、 call websocket service , The method of actively pushing messages
<?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: adopt uid, Push message to user
* User: Hehe
* 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' =>" Hello! , collection :{$price} element "
];
$ws->send(json_encode($data,JSON_UNESCAPED_UNICODE));
return " Send successfully \n";
usleep(100);
} catch (BadOpcodeException $e) {
throw new Exception($e->getMessage());
}
$ws->close();
}
}
}
2、 stay job Add writing task to
<?php
namespace addons\ByThirdagency\common\jobs;
use addons\ByThirdagency\common\services\WebSocketSendService;
/**
* Param: Order push messages to users
* Class SendMsgJob
* User: Hehe
* 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(' Push message to user :'.$res);
}catch (\Exception $exception){
\Yii::$app->byfLog->channel('WebSocket')->error(' Error pushing message to user '.$exception->getFile() . ':' . $exception->getLine() . ':' . $exception->getMessage() . PHP_EOL);
}
}
}
3、 Push message to asynchronous queue :
<?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: adopt uid, Push message to user
* User: Hehe
* 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: The push message task is added to the queue
* User: Hehe
* 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());
}
}
}
The command to manually push the message task queue test :
php yii web-socket-push/send-msg-job 112402 4.9999
4、web End connection websocket service , Receive messages
<!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">
// obtain url Parameters in
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // Construct a regular expression object with target parameters
var r = window.location.search.substr(1).match(reg); // Match target parameters
if (r != null) return unescape(r[2]); return null; // Return parameter value
}
// Usage method , url Contained in the id This parameter
var uid = getUrlParam("uid")
if ("WebSocket" in window)
{
console.log(' The received uid='+uid);
// establish webSocket object
//var ws = new WebSocket("wss://test.***********.cn/wss?uid="+uid); // test
// Triggered when connection is established
ws.onopen = function()
{
console.log(' Has established a connection with the boss behind the scenes ');
}
// Triggered when client receives server data
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log(' Received the message pushed by the boss :'+received_msg);
}
// Triggered when the connection is closed
ws.onclose = function(evt)
{
console.log(" Connection closed ...");
}
// Triggered when the connection is closed
ws.onerror = function()
{
console.log(" Connection error ...");
}
}
else
{
// Browser does not support WebSocket
alert(" Your browser does not support it WebSocket!");
}
function sendData() {
var msg = $("#msg").val();
ws.send(msg);
}
</script>
</head>
<body>
<input type="text" placeholder=" Please enter the text to send " id="msg">
<button onclick="sendData()"> Click Send </button>
</body>
</html>
5、 To configure 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
边栏推荐
- 如何在熊市中寻找机会?
- 数启扬帆,智聚人才 | 腾讯云数据库 & CSDN 工程师能力轻量认证发布会重磅来袭!...
- Pytorch model
- Mature case and source code of hash quiz game system development technology
- Hang Seng Electronics: lightdb, a financial distributed database, has passed a number of evaluations by China Academy of communications technology
- 腾讯汤道生:面向数实融合新世界,开发者是最重要的“建筑师”
- Mobile web training day-2
- 哈希竞猜游戏系统开发技术成熟案例及源码
- plt. Usage of savefig() and save path
- Vscode shortcut key
猜你喜欢

弹性盒子自动换行小Demo

Mobile web training day-2

Oceanwide micro fh511 single chip microcomputer IC scheme small household appliances LED lighting MCU screen printing fh511

PostgreSQL超越MySQL

895. 最长上升子序列

1015. picking flowers

中国数据库技术大会(DTCC)特邀科蓝SUNDB数据库专家精彩分享
![Buuctf:[wustctf2020] plain](/img/0f/a7973d3f7593f2464e48609e27d7bd.png)
Buuctf:[wustctf2020] plain

MySQL multi table joint query

投资98万美元的Saas项目失败了
随机推荐
895. 最长上升子序列
The English translation of heartless sword Zhu Xi's two impressions of reading
5A synchronous rectifier chip 20V to 12v2a/5v4.5a high current 24W high power synchronous rectifier chip high current step-down IC fs2462
Mobile web training day-2
Mature case and source code of hash quiz game system development technology
专业英语历年题
Arduino-ESP32闪存文件插件程序搭建和上传
如何在熊市中寻找机会?
认识启动函数,找到用户入口
PHP根据年月获取月初月末时间
Align content attribute in flex layout
Embedded development: seven techniques for estimating battery life
plt.savefig()的用法以及保存路径
电脑无线网络不显示网络列表应该如何解决
yii2编写swoole的websocket服务
895. longest ascending subsequence
Centos7: switch MySQL users and log in to MySQL
Jerry's wif interferes with Bluetooth [chapter]
MySQL多表联合查询
Complete backpack beginner chapter "suggestions collection"