swoole使用websocket及tcp实现一个h5聊天室效果代码

代码语言:phpcli

所属分类:通讯

代码描述:swoole使用websocket及tcp实现一个h5聊天室效果代码

代码标签: tcp 实现 一个 h5 聊天室 效果

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?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)
        ]);

        //监听WebSocket连接打开事件
        $this->serv->on('Open', function ($ws, $request) {
            $ws->push($request->fd, "hello, welcome\n");
        });

        //监听WebSocket消息事件
        $this->serv->on('Message', function ($ws, $frame) {
            $data = $frame->data;
            $res['data'] = $data;
            foreach ($ws->connections as $client) {
                if ($frame->fd == $client) {
                    $res['style'] = 'bubble me';
                } else {
                    $res['style'] = 'bubble you';
                }
                @$ws->push($client, json_encode($res, 256));
            }
        });

        //监听WebSocket连接关闭事件
        $this->serv->on('Close',
            function ($ws, $fd) {
                echo "client-{$fd} is closed\n";
            });



        $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) {
        echo "#### onStart ####".PHP_EOL;
        echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".PHP_EOL;
        echo "master_pid: {$serv->master_pid}".PHP_EOL;
        echo "manager_pid: {$serv->manager_pid}".PHP_EOL;
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onOpen($serv,
        $request) {
        echo "#### onOpen ####".PHP_EOL;
        echo "server: handshake success with fd{$request->fd}".PHP_EOL;
        $serv->task([
            'type' => 'login'
        ]);
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onTask($serv,
        $task_id,
        $from_id,
        $data) {
        echo "#### onTask ####".PHP_EOL;
        echo "#{$serv->worker_id} onTask: [PID={$serv->worker_pid}]: task_id={$task_id}".PHP_EOL;
        $msg = '';
        switch ($data['type']) {
            case 'login':
                $msg = '我来了...';
                break;
            case 'speak':
                $msg = $data['msg'];
                break;
        }
        foreach ($serv->connections as $fd) {
            $connectionInfo = $serv->connection_info($fd);
            if (isset($connectionInfo['websocket_status']) && $connectionInfo['websocket_status'] == 3) {
                $serv->push($fd, $msg); //长度最大不得超过2M
            }
        }
        $serv->finish($data);
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onFinish($serv, $task_id, $data) {
        echo "#### onFinish ####".PHP_EOL;
        echo "Task {$task_id} 已完成".PHP_EOL;
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onClose($serv, $fd) {
        echo "#### onClose ####".PHP_EOL;
        echo "client {$fd} closed".PHP_EOL;
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onMessage($serv, $frame) {
        echo "#### onMessage ####".PHP_EOL;
        echo "receive from fd{$frame->fd}:{$fra.........完整代码请登录后点击上方下载按钮下载查看

网友评论0