ホームページ  >  記事  >  PHPフレームワーク  >  thinkphp 6.0 swoole は WebSocket の使用を拡張します

thinkphp 6.0 swoole は WebSocket の使用を拡張します

藏色散人
藏色散人転載
2020-12-15 09:35:532766ブラウズ

以下は、thinkphp Framework のチュートリアル欄で、thinkphp 6.0 swoole 拡張 Websocket の使い方チュートリアル (think-swoole) を紹介します。必要としている!

thinkphp 6.0 swoole 拡張 Websocket 使用法チュートリアル (think-swoole)

まえがき

TP-SWOOLE の最新バージョンは大きく変更されており、この記事で提供されている方法はは使用できなくなりました。https://github.com/xavieryang007/think-swoole-demo/blob/master/doc/document/4.1-websocket.md を参照してください。

近日公開予定の tp6.0 が swoole に適応され、think-swoole 3.0 がリリースされ、socketio がデフォルトで適応されます。バージョン2.0とは使用方法が若干異なります。

Websocket は Http を継承します。WebSocket に接続する前に HTTP リクエストが必要です。現在のアドレスが WebSocket をサポートしている場合は、101 が返され、接続が確立されます。言い換えれば、サービスが WebSocket をサポートした後、要求されたすべての接続アドレスが WebSocket に接続できるわけではありませんが、接続する前に事前に適応させる必要があります。

パラメータ設定

WebSocket を使用したい場合は、設定で有効にする必要があります。WebSocket の下の Enable を 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'           => [],

ハンドラーとパーサーはカスタム WebSocket を大幅に容易にしますデフォルトのシステムには、socketio が統合されています。

この記事では、socketio の使い方を中心に紹介しますので、皆さんが soketio について一定の理解と使い方の基礎を持っていることを前提としています。

socketIo は、デフォルトでリクエスト アドレスの後に対応するパラメータを追加します。

同時に、socketio は http://url/socket.io を次のように認識します。デフォルトの / は、WebSocket サービスをサポートするアドレスです。 thinkphp 6.0 swoole は WebSocket の使用を拡張します

アドレス要求は tp-swoole3.0thinkphp 6.0 swoole は WebSocket の使用を拡張します

<?php namespace think\swoole\websocket\socketio;

use think\Config;
use think\Cookie;
use think\Request;

class Controller
{
    protected $transports = [&#39;polling&#39;, &#39;websocket&#39;];

    public function upgrade(Request $request, Config $config, Cookie $cookie)
    {
        if (!in_array($request->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 で内部処理され、プラグインの登録はサービス モードで実行されます。登録するには、tp-swoole サービス登録ファイル内のルート登録情報を表示できます。リンク ルールをカスタマイズする場合は、ルートを上書きできます。

<?php // +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

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 はデフォルトでデモを使用します

nbsp;html>


    <meta>
    <title>Title</title>
    <script></script>


<script>
    const socket = io(&#39;http://localhost:808&#39;);
    socket.emit("test", "your message");
    socket.on("test",function(res){console.log(res)});
</script>

Websocket ルーティング設定方法

アプリ ディレクトリに新しい websocket.php ファイルを作成します。リフレクションを使用しているため、クロージャパラメータ 名前を任意に定義することはできません。それ以外の場合は、名前を注入できません。最初のパラメータは websocket (現在の Websocket の Server オブジェクト) で、2 番目のパラメータ data はクライアントによって送信されたデータです。 Socketio Emit の最初のパラメータは、イベント名として使用される Websocket::on の最初のパラメータと同じです。

<?php /**
 * Author:Xavier Yang
 * Date:2019/6/5
 * Email:499873958@qq.com
 */

use \think\swoole\facade\Websocket;

Websocket::on("test", function (\think\swoole\Websocket $websocket, $data) {
    //var_dump($class);
    $websocket->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");
});

新しい WebSocket サービスを使用するには、上記の方法を参照してください。もちろん、tp-swoole3.0 には他にも多くの新機能があるので、試してみる必要があります。 thinkphp 6.0 swoole は WebSocket の使用を拡張します次の記事では私の使用プロセスも紹介します。

以上がthinkphp 6.0 swoole は WebSocket の使用を拡張しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はsegmentfault.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。