龙行博客

走路看风景,经历看人生,岁月留痕迹,人生留轨迹,17的历史,18的豪情,时间的匆忙,人生的风景,放开心胸往前走,成功再远行,放开理想往前走,梦想再行动。
现在位置:首页 > Swoole与WebSocket如何即时通讯,实现弹幕效果?

Swoole与WebSocket如何即时通讯,实现弹幕效果?

龙行        2021-12-27    255    0评论    

实现弹幕其实就和通讯,群聊类似,将消息推送给所有的客户端,不过前端的展示所有不同。

本地环境

后端 PHP 7.2.6、Swoole 4.3.1。

前端 HTML5 WebSocket、Canvas。


效果如图

终端效果批量版:

640.gif

640 (1).gif

手动版:

640 (2).gif

下面我们来看看代码是如何实现的。

后端处理文件:server.php

<?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("Close", [$this, 'onClose']);
        $this->serv->on("Task", [$this, 'onTask']);
        $this->serv->on("Finish", [$this, 'onFinish']);

        $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 ($connectionInfo['websocket_status'] == 3) {
                $serv->push($fd, $msg); //长度最大不得超过2M
            }
        }
        $serv->finish($data);
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onMessage($serv, $frame) {
        echo "#### onMessage ####".PHP_EOL;
        echo "receive from fd{$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}"
        .PHP_EOL;
        $serv->task(['type' => 'speak', 'msg' => $frame->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;
    }
}

$server = new Server();

前端:index.html

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="keywords" content="">
        <script src="js/canvasBarrage.js?v=17"></script>
        <title>视频弹幕Demo</title>
        <style>
            .canvas-barrage {
                position: absolute;
                width: 960px;
                height: 540px;
                pointer-events: none;
                z-index: 1;
            }
            .ui-input {
                height: 20px;
                width: 856px;
                line-height: 20px;
                border: 1px solid #d0d0d5;
                border-radius: 4px;
                padding: 9px 8px;
            }
            .ui-button {
                display: inline-block;
                background-color: #2486ff;
                line-height: 28px;
                text-align: center;
                border-radius: 4px;
                color: #fff;
                font-size: 14px;
            }
        </style>
    </head>
    <body>
        <canvas id="canvasBarrage" class="canvas-barrage"></canvas>
        <video id="videoBarrage" width="960" height="540" src="./video/video.mp4" controls></video>
            <p>
                <input class="ui-input" id="msg" name="value" value="发送弹幕" required>
                <input class="ui-button" type="button" id="sendBtn" value="发送弹幕">
            </p>
        <script>
            if ("WebSocket" in window) {
                // 弹幕数据
                var dataBarrage = [{
                    value: '',
                    time: 0, // 单位秒
                    speed: 0,
                    fontSize: 0
                }];

                var itemsColor = ['#FFA54F','#FF4040','#EE1289', '#8E8E38', '#3A5FCD', '#00EE76', 
                '#388E8E', '#76EEC6', '#87CEFF', '#7FFFD4'];

                var eleCanvas = document.getElementById('canvasBarrage');
                var eleVideo = document.getElementById('videoBarrage');

                var barrage = new CanvasBarrage(eleCanvas, eleVideo, {
                    data: dataBarrage
                });

                var wsServer = 'ws://10.211.55.3:9501';
                var ws = new WebSocket(wsServer);

                ws.onopen = function (evt) {
                    if (ws.readyState == 1) {
                        console.log('WebSocket 连接成功...');
                    } else {
                        console.log('WebSocket 连接失败...');
                    }
                };

                ws.onmessage = function (evt) {

                    barrage.add({
                        value: evt.data,
                        time: eleVideo.currentTime,
                        speed: 5,
                        color: itemsColor[Math.floor(Math.random()*itemsColor.length)]
                        // 其它如 fontSize, opacity等可选
                    });
                    console.log('Retrieved data from server: ' + evt.data);
                };

                ws.onerror = function (evt) {
                    alert('WebSocket 发生错误');
                    console.log(evt);
                };

                ws.onclose = function() {
                    alert('WebSocket 连接关闭');
                    console.log('WebSocket 连接关闭...');
                };

                var msg;
                var sendBtn = document.getElementById('sendBtn');
                sendBtn.onclick = function(){
                    if (ws.readyState == 1) {
                        msg = document.getElementById('msg').value;
                        ws.send(msg);
                    } else {
                        alert('WebSocket 连接失败');
                    }
                };
            } else {
                alert("您的浏览器不支持 WebSocket!");
            }
            </script>
    </body>
</html>

实现过程需要注意的几个地方

1、官网没有提供群聊的方法,所以群聊的处理方法我们用循环就好了。

单聊:

$serv->push($fd, $msg);

群聊:

foreach ($serv->connections as $fd) {
    $serv->push($fd, $msg);
}

2、如何模拟批量弹幕效果?

可以使用 swoole_timer_tick ,比如:

swoole_timer_tick(50, function () use($serv){
    $serv->task([
        'type' => 'login'
    ]);
});

3、前端使用的弹幕插件:canvasBarrage.js

本教程实现的弹幕插件地址:http://www.zhangxinxu.com/wordpress/?p=6386

其他的比如有:Jquery.barrager.jsJquery.danmu.jsDanMuer.js ,更多实现方法可以自己去研究与尝试!

轉載自:https://www.cnblogs.com/xinliangcoder/p/10800910.html

评论一下 分享本文 赞助站长

赞助站长X

扫码赞助站长
联系站长
龙行博客
  • 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《龙行博客》。
  • 本文网址:https://www.liaotaoo.cn/380.html
  • 上篇文章:数学函数在PHP中的相关应用
  • 下篇文章:Laravelapi 自定义 response 格式
  • php tp5 css js swoole tp6 thinkphp6
快捷导航
联系博主
在线壁纸
给我留言
四四五五
音乐欣赏
返回顶部