当前位置:网站首页>Yii2 writing the websocket service of swoole
Yii2 writing the websocket service of swoole
2022-06-28 13:28:00 【Hehe PHPer】
One 、 see PHP Of swoole Expand
open phpinfo, Search for , If it is not installed, it needs to be installed
Two 、 Start writing swoole Service code :
Inquiry list :/console/controllers/WebSocketController.php
| Have a problem 1: It is impossible to realize the uid Push messages to specific merchants , Only connected users can push all users |
| Solution :1、 Client connection websocket In service , To the merchant uid, Server side client Receive merchant's uid, adopt redis The merchant's uid As key, Splice fixed prefix , Client connected fd Value , For storage ; 2、 Take the initiative to push server Connect server client When actively pushing messages ,json Transmit the information of the merchant to be pushed in the string uid; 3、 Server side message After receiving the message , analysis json Merchants passing through the middle uid, adopt uid Of key Values obtained redis Of the merchant connection stored in fd value , adopt fd Value to push message to merchant ; 4、 Solve the problem according to the merchant uid The problem of pushing a specific message to a specific merchant ; |
namespace console\controllers;
use \Swoole\WebSocket\Server;
use Yii;
use yii\console\Controller;
use yii\helpers\Json;
class WebSocketController extends Controller
{
/**
* @var Server
*/
public $serv;
public function actionRun()
{
// To configure ssl Encrypted connection , SWOOLE_PROCESS, SWOOLE_SOCK_TCP|SWOOLE_SSL
$this->serv = new Server("0.0.0.0", 9503);
$this->serv->set([
'worker_num' => 10, // Number of processes opened ⼀ General cup Check the number 1-4 times
'task_worker_num' => 10, // To configure Task The number of processes .
'daemonize' => 1, // Set up daemonize => true when , The program will go into the background and run as a daemon . This must be enabled for long-running server-side programs . If the daemon is not enabled , When ssh After the terminal exits , The program will be terminated .
'max_request' => 10000, // Set up worker Maximum number of tasks for the process .
'dispatch_mode' => 5, //uid dispatch UID Distribute Call in user code Server->bind() Bind a connection 1 individual uid. Then the bottom layer according to UID Assign values to different Worker process .
'open_eof_check' => true,
'package_eof' => PHP_EOL,
'log_file' => Yii::getAlias('@runtime/swoole_below_cps.log'),
'reload_async' => true, // The main purpose of enabling is to ensure that when the service is overloaded , A concurrent or asynchronous task can end normally .
//'enable_reuse_port' => true, // After enabling port reuse , You can repeatedly start to listen to the same port Server Program
'heartbeat_idle_time' => 600,
'heartbeat_check_interval' => 60,
// 'ssl_cert_file' => EnvHelper::get('SSL_PEM'), //ssl Encryption profile
// 'ssl_key_file' => EnvHelper::get('SSL_KEY'), //ssl Encryption configuration key file
]);
$this->serv->on('Start', [$this, 'onStart']);
$this->serv->on('Open', [$this, 'onOpen']);
$this->serv->on('Message', [$this, 'onMessage']);
$this->serv->on('Request', [$this, 'onRequest']);
$this->serv->on('Receive', [$this, 'onReceive']);
$this->serv->on('Task', [$this, 'onTask']);
$this->serv->on('Finish', [$this, 'onFinish']);
//dd(' Don't start ');
$this->serv->start();
}
public function onStart(Server $server)
{
static::log(' platform Websocket start-up '.$server->worker_id . PHP_EOL);
}
/**
* Param: When WebSocket This function will be called back after the client has established a connection with the server and completed the handshake .
* User: Hehe
* Date: 2022/6/13
* @param Server $server
* @param $request
* @return void
*/
public function onOpen(Server $server, $request) {
// receive uid
$uid = $request->get['uid'];
//$type = $request->get['type'];
static::log(" Living platform - Establishing a connection : user uid= {$uid}, fd={$request->fd} Establishing a connection \n");
if(!empty($uid)){
// Users to be received ID Stored in redis in
$redisKey = "BELOWCPSWEBSOCKET:".$uid;
$redis = \Yii::$app->redis;
$res = $redis->set($redisKey,$request->fd);
static::log(" platform - Users to be received ID Stored in redis in :$res\n");
}
}
/** This function is called back when the server receives the data frame from the client .
* Param:
* User: Hehe
* Date: 2022/6/13
* @param Server $server
* @param $frame
* @return void
*/
public function onMessage(Server $server, $frame)
{
static::log('websocket The service received a message from Laotie :' . $frame->data);
$data = json_decode($frame->data, true);
static::log('websocket The service decrypts the message sent by Laotie :' . $data['uid']."\n");
// according to uid obtain redis Medium fd, according to fd Push messages to users
if(!empty($data['uid'])){
// obtain redis Users in fd
$redisKey = "BELOWCPSWEBSOCKET:".$data['uid'];
$redis = \Yii::$app->redis;
$u_fd = $redis->get($redisKey);
static::log("websocket Service to get old railway connection fd={$u_fd} Send a message \n");
if($server->isEstablished($u_fd)){
$server->push($u_fd, $data['msg']);
}
}
// else{
// // No, uid
// foreach ($server->connections as $fd) {
// if ($server->isEstablished($fd)) {
// $server->push($fd, $data['msg']);
// }
// }
// }
}
/**
* Param: receive http Request from get obtain message The value of the parameter , Push to users
* User: Hehe
* Date: 2022/6/13
* @param Server $serv
* @param $response
* @return void
*/
public function onRequest(Server $serv, $response){
$uid = $serv->get['uid'];
static::log('websocket Service received :'.$uid);
foreach ($this->serv->connections as $fd) {
// We need to judge whether it is right or not websocket Connect , Otherwise, it may be push Failure
if ($this->serv->isEstablished($fd)) {
$this->serv->push($fd, $serv->get['message']);
}
}
}
public function onReceive(Server $serv, $fd, $reactor_id, $data){
$conn = $serv->connection_info($fd);
echo "worker_id: " . $serv->worker_id . PHP_EOL;
if (empty($conn['uid'])) {
$uid = $fd + 1;
if ($serv->bind($fd, $uid)) {
$serv->send($fd, "bind {$uid} success");
}
} else {
if (!isset($serv->fdlist[$fd])) {
$serv->fdlist[$fd] = $conn['uid'];
}
print_r($serv->fdlist);
foreach ($serv->fdlist as $_fd => $uid) {
$serv->send($_fd, "{$fd} say:" . $data);
}
}
}
/**
* Processing tasks
* @param \Swoole\Server $serv
* @param int $task_id
* @param int $from_id
* @param string $data
*/
public function onTask(Server $serv, int $task_id, int $from_id, string $data)
{
static::log(' Receive a new task ');
$data = Json::decode($data, true);
$serv->finish($data);
}
/**
* @param Server $server
* @param int $task_id
* @param mixed $data
*/
public function onFinish(Server $server, int $task_id, $data)
{
static::log(' Task to complete ');
}
/**
* @param mixed $message
*/
private static function log($message)
{
$str = "[" . date('Y-m-d H:i:s') . '] ';
if (is_string($message)) {
$str .= $message;
}
if (is_array($message)) {
$str .= var_export($message, true);
}
$str .= PHP_EOL;
// echo $str;
\Yii::$app->byfLog->channel('BelowCpsWebSocket')->info($str);
}
}3、 ... and 、 start-up / stop it
1、 Start command :php yii web-socket/run
2、 Stop the service : View the running service according to the port number :netstat -nap | grep 9503
kill id
边栏推荐
- How to display the server list of the electric donkey, and how to update the eMule server list
- 股票网上开户及开户流程怎样?手机开户是安全么?
- 完全背包 初学篇「建议收藏」
- pytorch主要模块
- Mobile web training day-2
- Latest summary! 30 provinces announce 2022 college entrance examination scores
- Resume template Baidu online disk
- 简历模板百度网盘自取
- Mobile web training -flex layout test question 1
- (原创)【MAUI】一步一步实现“悬浮操作按钮”(FAB,Floating Action Button)
猜你喜欢

移动Web实训DAY-1

ShareIt has outstanding strength and landed in the top 7 of the global IAP strength list

Stm32f1 and stm32cubeide programming example - matrix keyboard driver

PHP crawls web pages for specific information

flex布局中的align-content属性

StackOverflow 2022数据库年度调查

Visual design tutorial of word cloud

新品体验:阿里云新一代本地SSD实例i4开放公测

scratch旅行相册 电子学会图形化编程scratch等级考试一级真题和答案解析2022年6月

2. 01背包问题
随机推荐
Unit test ci/cd
flex布局中的align-content属性
Stm32f1 and stm32cubeide programming example - matrix keyboard driver
其他国产手机未能填补华为的空缺,苹果在高端手机市场已无对手
List set to array
Shareit a une force exceptionnelle et se connecte au top 7 de la liste mondiale des forces IAP
求职简历的书写技巧
同花顺上怎么进行开户啊, 安全吗
泛海微FH511单片机IC方案小家电LED照明MCU丝印FH511
完全背包 初学篇「建议收藏」
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"?
华泰证券开户怎么开 怎么办理开户最安全
yii2连接websocket服务实现服务端主动推送消息给客户端
电脑无线网络不显示网络列表应该如何解决
Which company has a low rate for opening a securities account? How to open an account is the safest
弹性盒子自动换行小Demo
海思35xx实现GT911触摸屏功能「建议收藏」
How to solve the data inconsistency between redis and MySQL?
Complete backpack beginner chapter "suggestions collection"
Forecast and Analysis on market scale and development trend of China's operation and maintenance security products in 2022