+
95
-

swoole如何设置同时监听不同协议的不同端口?

php

请问swoole如何设置同时监听不同协议的不同端口?比如我要开启websocket http udp三个服务不同端口监听,请问怎么写?

网友回复

+
15
-
<?php

class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new swoole_websocket_server("0.0.0.0", 9501);
        $this->serv->set([
            'worker_num'      => 2, //开启2个worker进程
            'max_request'     => 4, //每个worker进程 max_request设置为4次
            'task_worker_num' => 4, //开启4个task进程
            'dispatch_mode'   => 4, //数据包分发策略 - IP分配
            'daemonize'       => false, //守护进程(true/false)
        ]);

        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('Open', [$this, 'onOpen']);
        $this->serv->on("Message", [$this, 'onMessage']);
        $this->serv->on("Request", [$this, 'onRequest']);
        $this->serv->on("Close", [$this, 'onClose']);
        $this->serv->on("Task", [$this, 'onTask']);
        $this->serv->on("Finish", [$this, 'onFinish']);

        //监听 9502 端口
        $tcp = $this->serv->listen("0.0.0.0", 9502, SWOOLE_SOCK_TCP);
        $tcp->set([
            'worker_num'      => 2, //开启2个worker进程
            'max_request'     => 4, //每个worker进程 max_request设置为4次
            'dispatch_mode'   => 2, //数据包分发策略 - 固定模式

            //固定包头+包体协议
            'open_length_check'     => true,
            'package_max_length'    => '8192',
            'package_length_type'   => 'N',
            'package_length_offset' => '0',
            'package_body_offset'   => '4',
        ]);
        $tcp->on("Receive", [$this, 'onReceive']);

        //监听 9503 端口
        $udp = $this->serv->listen("0.0.0.0", 9503, SWOOLE_SOCK_UDP);
        $udp->set([
            'worker_num'      => 2, //开启2个worker进程
            'max_request'     => 4, //每个worker进程 max_request设置为4次
            'dispatch_mode'   => 2, //数据包分发策略 - 固定模式
        ]);
        $udp->on("Packet", [$this, 'onPacket']);

        $this->serv->start();
    }

    public function onStart($serv) ...

点击查看剩余70%

我知道答案,我要回答