Home  >  Article  >  PHP Framework  >  thinkphp 6.0 swoole extends the use of websocket

thinkphp 6.0 swoole extends the use of websocket

藏色散人
藏色散人forward
2020-12-15 09:35:532676browse

The following is the tutorial column of thinkphp framework to introduce to you the thinkphp 6.0 swoole extended websocket usage tutorial (think-swoole). I hope it will be helpful to friends in need!

thinkphp 6.0 swoole extended websocket usage tutorial (think-swoole)

Preface

The latest version of TP-SWOOLE has changed a lot, and the method provided in this article can no longer be used. , you can refer to https://github.com/xavieryang007/think-swoole-demo/blob/master/doc/document/4.1-websocket.md

Introduction

Coming soon tp6.0 has been adapted to swoole. And think-swoole 3.0 has been launched, and socketio is adapted by default. The usage method is slightly different from version 2.0.

Websocket inherits from Http. An HTTP request is required before connecting to websocket. If the current address supports websocket, 101 will be returned, and then the connection will be made. In other words, it is not that after my service supports websocket, every connection address requested can be connected to the websocket, but it needs to be pre-adapted before it can be connected.

Parameter configuration

If you want to use websocket, you need to enable it in the configuration. Set enable under websocket to true

 'server'           => [
        'host'      => '0.0.0.0', // 监听地址
        'port'      => 808, // 监听端口
        'mode'      => SWOOLE_PROCESS, // 运行模式 默认为SWOOLE_PROCESS
        'sock_type' => SWOOLE_SOCK_TCP, // sock type 默认为SWOOLE_SOCK_TCP
        'options'   => [
            'pid_file'              => runtime_path() . 'swoole.pid',
            'log_file'              => runtime_path() . 'swoole.log',
            'daemonize'             => false,
            // Normally this value should be 1~4 times larger according to your cpu cores.
            'reactor_num'           => swoole_cpu_num(),
            'worker_num'            => swoole_cpu_num(),
            'task_worker_num'       => 4,//swoole_cpu_num(),
            'enable_static_handler' => true,
            'document_root'         => root_path('public'),
            'package_max_length'    => 20 * 1024 * 1024,
            'buffer_output_size'    => 10 * 1024 * 1024,
            'socket_buffer_size'    => 128 * 1024 * 1024,
            'max_request'           => 3000,
            'send_yield'            => true,
        ],
    ],
    'websocket'        => [
        'enabled'       => true,// 开启websocket
        'handler'       => Handler::class,  //自定义wbesocket绑定类
        'parser'        => Parser::class, //自定义解析类
        'route_file'    => base_path() . 'websocket.php',
        'ping_interval' => 25000,
        'ping_timeout'  => 60000,
        'room'          => [
            'type'        => TableRoom::class,
            'room_rows'   => 4096,
            'room_size'   => 2048,
            'client_rows' => 8192,
            'client_size' => 2048,
        ],
    ],
    'auto_reload'      => true,
    'enable_coroutine' => true,
    'resetters'        => [],
    'tables'           => [],

handler and parser greatly facilitate custom websocket services. The default system integrates socketio.

This article mainly introduces how to use socketio. It is assumed that everyone has a certain understanding and usage foundation of socketio.

socketIo will add corresponding parameters after the request address by default

thinkphp 6.0 swoole extends the use of websocket

At the same time, socketio will think http://url/socket.io by default / is the address that supports websocket service.

thinkphp 6.0 swoole extends the use of websocket

The address request has been processed internally in tp-swoole3.0

param('transport'), $this->transports)) {
            return json(
                [
                    'code'    => 0,
                    'message' => 'Transport unknown',
                ],
                400
            );
        }

        if ($request->has('sid')) {
            $response = response('1:6');
        } else {
            $sid     = base64_encode(uniqid());
            $payload = json_encode(
                [
                    'sid'          => $sid,
                    'upgrades'     => ['websocket'],
                    'pingInterval' => $config->get('swoole.websocket.ping_interval'),
                    'pingTimeout'  => $config->get('swoole.websocket.ping_timeout'),
                ]
            );
            $cookie->set('io', $sid);
            $response = response('97:0' . $payload . '2:40');
        }

        return $response->contentType('text/plain');
    }

    public function reject(Request $request)
    {
        return json(
            [
                'code'    => 3,
                'message' => 'Bad request',
            ],
            400
        );
    }
}

TP6.0, the plug-in registration is carried out in service mode To register, you can view the route registration information in the tp-swoole service registration file. If you want to customize the link rules, you can override the route.


// +----------------------------------------------------------------------

namespace think\swoole;

use Swoole\Http\Server as HttpServer;
use Swoole\Websocket\Server as WebsocketServer;
use think\App;
use think\Route;
use think\swoole\command\Server as ServerCommand;
use think\swoole\facade\Server;
use think\swoole\websocket\socketio\Controller;
use think\swoole\websocket\socketio\Middleware;

class Service extends \think\Service
{
    protected $isWebsocket = false;

    /**
     * @var HttpServer | WebsocketServer
     */
    protected static $server;

    public function register()
    {
        $this->isWebsocket = $this->app->config->get('swoole.websocket.enabled', false);

        $this->app->bind(Server::class, function () {
            if (is_null(static::$server)) {
                $this->createSwooleServer();
            }

            return static::$server;
        });

        $this->app->bind('swoole.server', Server::class);

        $this->app->bind(Swoole::class, function (App $app) {
            return new Swoole($app);
        });

        $this->app->bind('swoole', Swoole::class);
    }

    public function boot(Route $route)
    {
        $this->commands(ServerCommand::class);
        if ($this->isWebsocket) {
            $route->group(function () use ($route) {
                $route->get('socket.io/', '@upgrade');
                $route->post('socket.io/', '@reject');
            })->prefix(Controller::class)->middleware(Middleware::class);
        }
    }

    /**
     * Create swoole server.
     */
    protected function createSwooleServer()
    {
        $server     = $this->isWebsocket ? WebsocketServer::class : HttpServer::class;
        $config     = $this->app->config;
        $host       = $config->get('swoole.server.host');
        $port       = $config->get('swoole.server.port');
        $socketType = $config->get('swoole.server.socket_type', SWOOLE_SOCK_TCP);
        $mode       = $config->get('swoole.server.mode', SWOOLE_PROCESS);

        static::$server = new $server($host, $port, $mode, $socketType);

        $options = $config->get('swoole.server.options');

        static::$server->set($options);
    }
}

Socketio uses demo by default

nbsp;html>


    
    Title
    




Websocket routing configuration method

Create a new websocket.php file in the app directory. Note that due to the use of reflection, closure parameters The name cannot be defined arbitrarily, otherwise it cannot be injected. The first parameter is websocket, which is the Server object of the current websocket, and the second parameter data is the data sent by the client. The first parameter of socketio emit is the same as the first parameter of Websocket::on, which is used as the event name.

emit("test", "asd");
});

Websocket::on("test1", function ($websocket, $data) {
    $websocket->emit("test", "asd");
});

Websocket::on("join", function (\think\swoole\Websocket $websocket, $data) {
    $websocket->join("1");
});

thinkphp 6.0 swoole extends the use of websocket

Refer to the above method to use the new websocket service. Of course, tp-swoole3.0 also has many other new features, which you need to explore and try.
I will also share my usage process with you in the next article.

The above is the detailed content of thinkphp 6.0 swoole extends the use of websocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete