Swoole与WebSocket 进行及时通讯,实现视频弹幕效果
2020-03-08 13:19:56 来源:admin 点击:803
//后端处理文件: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> <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"></canvas> <video id="videoBarrage" width="960" height="540" src="./video/video.mp4" controls></video> <p> <input id="msg" name="value" value="发送弹幕" required> <input 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> //实现过程需要注意的几个地方 //一、官网没有提供群聊的方法,所以群聊的处理方法我们用循环就好了。 //单聊: $serv->push($fd, $msg); //群聊: foreach ($serv->connections as $fd) { $serv->push($fd, $msg); } //二、如何模拟批量弹幕效果? 可以使用 swoole_timer_tick ,比如: swoole_timer_tick(50, function () use($serv){ $serv->task([ 'type' => 'login' ]); }); 三、前端使用的弹幕插件:canvasBarrage.js 本教程实现的弹幕插件地址:http://www.zhangxinxu.com/wordpress/?p=6386