In the previous article, one of the sockets was configured to handle handler events as app\ Webscoket \Manager. Let’s look at what methods need to be done in this class

Socket listening event

app\event.php

Return ['listen' => ['swoole.workerStart' => [\app\ webSocket \SwooleWorkerStart::class],// Socket start event 'swoole.workerStop' => [],// Socket stop event 'swoole.workerError' => [],// Socket error event 'swoole.workerexit' => [],// execute event only after asynchronous restart ]].Copy the code

Internal structure of the SwooleWorkerStart class

<? php namespace app\webscoket; Class SwooleWorkerStart {public function __construct() {} // the event is executed as the result of the think\swoole\App instantiation handle($event): void { if ($event->make('swoole.server')->worker_id === 0 && $event->config->get('swoole.websocket.enable',false)) { $this->ping(); $this->ping(); $this->timer(); }}}Copy the code

Internal structure of the app webscoket Manager class

Once the websocket.handle in the swoole.php configuration is reconfigured and the class is overwritten then the events that were built in will be lost and will have to be handled

<? php namespace app\webscoket; use think\swoole\Websocket; use Swoole\Websocket\Frame; ** @param int $fd * @param Request $Request */ public Function onOpen($fd, \think\Request $Request) {$this->server->close($fd); $this->server->push($fd, $data); $this->server->push($fd, $data); Public function onMessage(Frame $Frame) {//$Frame ->fd {"type":"test","data":{"message":" hello "}} ** @param int $fd connection * @param int $reactorId Thread ID */ Public function onClose($fd, $reactorId) {if ($fd, $reactorId) {Copy the code

To deal with Ping

If not, call app(‘swoole.server’)->close($fd) to disable it

This method is written in the SwooleWorkerStart class

use Swoole\Timer; protected function ping() { Timer::tick(1500, function (int $timer_id) { /** @var Swoole\Server $server*/ $server = app('swoole.server'); Foreach ($server->connections as $fd) {if ($server->isEstablished($fd)) {if ($server->isEstablished($fd)) $server->close($fd); $server->close($fd); }}}); }Copy the code

Swoole\Server->isEstablished()

Check for a valid Websocket connection