thinkphp 6.0 swoole, 웹소켓 사용 확장

藏色散人
풀어 주다: 2020-12-15 09:35:53
앞으로
2881명이 탐색했습니다.

다음 튜토리얼 칼럼인 thinkphp Framework에서는 thinkphp 6.0 swoole 확장 웹소켓 사용법 튜토리얼(think-swoole)을 소개하겠습니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

thinkphp 6.0 swoole 확장 웹소켓 사용법 튜토리얼(think-swoole)

머리말

최신 버전의 TP-SWOOLE은 많이 변경되었습니다. 이 글에서 제공하는 방법은 더 이상 사용할 수 없습니다. /github.com/xavieryang007 /think-swoole-demo/blob/master/doc/%E6%96%87%E6%A1%A3/4.1-websocket.md

소개

다가오는 tp6.0은 그리고 think-swoole 3.0이 출시되고 소켓티오가 기본적으로 적용됩니다. 2.0버전과 사용법이 조금 다릅니다.

Websocket은 Http에서 상속됩니다. websocket에 연결하기 전에 HTTP 요청이 필요합니다. 현재 주소가 websocket을 지원하는 경우 101이 반환된 후 연결됩니다. 즉, 내 서비스가 websocket을 지원한 후에는 요청한 모든 연결 주소가 websocket에 연결될 수 있는 것이 아니라, 연결되기 전에 미리 적응되어야 합니다.

매개변수 구성

웹소켓을 사용하려면 구성에서 이를 활성화하고 웹소켓에서 활성화를 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'           => [],
로그인 후 복사

핸들러와 파서는 사용자 정의 웹소켓 서비스를 크게 촉진하며 기본 시스템은 소켓io를 통합합니다.

이 글에서는 주로 소켓티오 사용법을 소개합니다. 모든 사람이 소켓티오에 대해 어느 정도 이해하고 사용하는 기초를 가지고 있다고 가정합니다.

socketIo는 기본적으로 요청 주소 뒤에 해당 매개변수를 추가합니다

thinkphp 6.0 swoole, 웹소켓 사용 확장

동시에 기본적으로 Socketio는 http://url/socket.io/를 웹소켓 서비스를 지원하는 주소로 간주합니다.

thinkphp 6.0 swoole, 웹소켓 사용 확장

주소 요청은 tp-swoole3.0

<?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 라우팅 구성 방법

app 디렉토리에 새로운 websocket.php 파일을 생성합니다. 리플렉션을 사용하기 때문에 클로저 매개변수 이름을 임의로 정의할 수 없다는 점에 유의하세요. 그렇지 않으면 주사할 수 없습니다. 첫 번째 파라미터는 현재 웹소켓의 Server 객체인 websocket이고, 두 번째 파라미터 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");
});
로그인 후 복사

thinkphp 6.0 swoole, 웹소켓 사용 확장

위의 방법을 참고하여 새로운 웹소켓 서비스를 이용해보세요. 물론 tp-swoole3.0에는 탐색하고 시도해야 할 다른 많은 새로운 기능도 있습니다.
다음 글에서는 사용 과정도 공유하겠습니다.

위 내용은 thinkphp 6.0 swoole, 웹소켓 사용 확장의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!