文章来自:新亮笔记
链接:https://www.cnblogs.com/xinliangcoder/p/10800910.html
作者:新亮点击加入:PHP自学中心交流③群
商务合作: 请加微信(QQ):2230304070
视频教程推荐
以下视频教程的网址:http://blog.startphp.cn
已经更改为:http://www.mano100.cn 请知悉!
精选文章正文
在上两篇文章,小编用原生的websocket实现即时通信:PHP实时消息推送,你在用websocket吗? 里就介绍了什么是websocket以及特性,原理和实现方法,再到用workerman实现即时通信的教程:PHP实时消息推送,你会不会用workerman,都大致了解到了,今天这篇主要给大家介绍swoole与websocket实现即时通讯,实现视频弹幕效果
实现弹幕其实就和通讯,群聊类似,将消息推送给所有的客户端,不过前端的展示所有不同。
本地环境
后端 PHP 7.2.6、Swoole 4.3.1。
前端 HTML5 WebSocket、Canvas。
效果如图
终端效果批量版:
手动版:
下面我们来看看代码是如何实现的。
后端处理文件: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>
实现过程需要注意的几个地方
一、官网没有提供群聊的方法,所以群聊的处理方法我们用循环就好了。
单聊:
$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
其他的比如有:Jquery.barrager.js,Jquery.danmu.js,DanMuer.js ,更多实现方法可以自己去研究与尝试!
以上是本文的全部内容,希望对大家的学习有帮助,也希望大家多多支持 php自学中心 ,学习与交流少不了一个圈子,点击加技术群:PHP自学中心交流③群
文章评论