Detailed explanation of websocket example of Yii2 combined with Workerman

  • 2021-11-02 00:01:34
  • OfStack

Preface

This article mainly introduces the related contents of websocket combining Yii2 with Workerman. Both of them are good things, so I wonder if they can be combined, so that some services can be smoothly migrated to Workerman when Yii2 has bottlenecks. The following words are not much to say, let's take a look at the detailed introduction with this site

The steps are as follows

1. Install workerman


composer require workerman/workerman

2. Start workerman

Create an commands/WorkermanWebSocketController. php file

Create the actionIndex () function to start with the following code


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}

Add initialization module


public function initWorker()
{
 $ip = isset($this->config['ip']) ? $this->config['ip'] : $this->ip;
 $port = isset($this->config['port']) ? $this->config['port'] : $this->port;
 $wsWorker = new Worker("websocket://{$ip}:{$port}");

 // 4 processes
 $wsWorker->count = 4;

 // Emitted when new connection come
 $wsWorker->onConnect = function ($connection) {
 echo "New connection\n";
 };

 // Emitted when data received
 $wsWorker->onMessage = function ($connection, $data) {
 // Send hello $data
 $connection->send('hello ' . $data);
 };

 // Emitted when connection closed
 $wsWorker->onClose = function ($connection) {
 echo "Connection closed\n";
 };
}

Add startup module


/**
 * workman websocket start
 */
public function start()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'start';
 if ($this->daemon) {
 $argv[2] = '-d';
 }

 // Run worker
 Worker::runAll();
}

Add a stop module


/**
 * workman websocket stop
 */
public function stop()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'stop';
 if ($this->gracefully) {
 $argv[2] = '-g';
 }

 // Run worker
 Worker::runAll();
}

Add Restart Module


 
/**
 * workman websocket restart
 */
public function restart()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'restart';
 if ($this->daemon) {
 $argv[2] = '-d';
 }

 if ($this->gracefully) {
 $argv[2] = '-g';
 }

 // Run worker
 Worker::runAll();
}

Add an overloaded module


/**
 * workman websocket reload
 */
public function reload()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'reload';
 if ($this->gracefully) {
 $argv[2] = '-g';
 }

 // Run worker
 Worker::runAll();
}

Add status module


/**
 * workman websocket status
 */
public function status()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'status';
 if ($this->daemon) {
 $argv[2] = '-d';
 }

 // Run worker
 Worker::runAll();
}

Add link number module


/**
 * workman websocket connections
 */
public function connections()
{
 $this->initWorker();
 //  Reset parameters to match Worker
 global $argv;
 $argv[0] = $argv[1];
 $argv[1] = 'connections';

 // Run worker
 Worker::runAll();
}

3. Front-end call


<script>
 // Create WebSocket connection.
 const ws = new WebSocket('ws://{{ app.request.hostName }}:2347/'); //  Here is the domain name of the website obtained. When testing, you can change it to your own local one ip Address 

 // Connection opened
 ws.addEventListener('open', function (event) {
 ws.send('Hello Server!');
 });

 // Listen for messages
 ws.addEventListener('message', function (event) {
 console.log('Message from server ', event.data);
 });

 setTimeout(function() {
 ws.send('ssssss');
 }, 10000);

</script>

4. config Parameter Configuration

Modify console. php and add the following code


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
0

5. nginx Configuration

Why do you use nginx? It is impossible for us to use ip directly when we deploy it normally. This household has potential safety hazards, so it is best to bind a domain name


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
1

Re-nginx


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
2

Then add the code of step 3 to the view made by yourself. If there is no problem, websocket can communicate normally after starting.

6. Start workerman websocket


//  Start 
./yii workerman-web-socket -s start -d

If there is no problem, you will get a result similar to the following


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
4

7. Others

The complete code for commands/WorkermanWebSocketController. php is as follows


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
5

Other commands supported by workerman websocket

Restart


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
6

Heavy load


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
7

Status


$ ./yii workerman-web-socket -s status -g
Workerman[workerman-web-socket] status 
----------------------------------------------GLOBAL STATUS----------------------------------------------------
Workerman version:3.5.13   PHP version:7.1.16
start time:2018-09-10 11:22:15 run 0 days 0 hours 
load average: 1.79, 2, 2   event-loop:\Workerman\Events\Swoole
1 workers  4 processes
worker_name exit_status  exit_count
none   0    12
----------------------------------------------PROCESS STATUS---------------------------------------------------
pid memory listening     worker_name connections send_fail timers total_request qps status
8283 4M  websocket://127.0.0.1:2346 none   0   0   0  0    0  [idle]
8284 4M  websocket://127.0.0.1:2346 none   0   0   0  0    0  [idle]
8285 4M  websocket://127.0.0.1:2346 none   0   0   0  0    0  [idle]
8286 4M  websocket://127.0.0.1:2346 none   0   0   0  0    0  [idle]
----------------------------------------------PROCESS STATUS---------------------------------------------------
Summary 16M  -       -   0   0   0  0    0  [Summary] 

Number of connections


public function actionIndex()
{
 if ('start' == $this->send) {
 try {
  $this->start($this->daemon);
 } catch (\Exception $e) {
  $this->stderr($e->getMessage() . "\n", Console::FG_RED);
 }
 } else if ('stop' == $this->send) {
 $this->stop();
 } else if ('restart' == $this->send) {
 $this->restart();
 } else if ('reload' == $this->send) {
 $this->reload();
 } else if ('status' == $this->send) {
 $this->status();
 } else if ('connections' == $this->send) {
 $this->connections();
 }
}
9

I am temporarily connected here, so there is no connection information

Stop


$ ./yii workerman-web-socket -s stop   
Workerman[workerman-web-socket] stop 
Workerman[workerman-web-socket] is stopping ...
Workerman[workerman-web-socket] stop success

Summarize


Related articles: