PHP大道至简之Swoole伪直播功能
伪直播功能Websocket服务器socket 通信技术就是两台联网的计算机之间交换数据的技术,这就是 socket 的全部内容了吗?是的!socket 编程远比想象中的简单很多,阅读完这套简明的入门教程你就能胜任简单的 socket 编程了。创建websockt服务代码如下error_reporting(-1);
//创建socket服务
$ws = new swoole_websocket_server("0.0.0.0", 9502);
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
//推送消息给所有用户
foreach($ws->connections as $fd){
$ws->push($fd, $frame->data);
}
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
//启动服务
$ws->start();
Websocket客户端socket 通信技术就是两台联网的计算机之间交换数据的技术,这就是 socket 的全部内容了吗?是的!socket 编程远比想象中的简单很多,阅读完这套简明的入门教程你就能胜任简单的 socket 编程了。创建websocket客户端
代码如下//连接服务器
const socket = new WebSocket('ws://lm.com:9502');
//Connection opened
socket.addEventListener('open', function (event) {
//发送消息给服务器
socket.send('Hello Server! im websockt');
});
// Listen for messages
socket.addEventListener('message', function (event) {
//接收服务器返回信息
console.log('Message from server ', event.data);
});
伪直播主播页面
html<body>
<video id="myVideo" src="./video/tikto.mp4" style="height:auto;width: 350px;" controls=true muted=true></video>
<canvas id="myCanvas" width="350" height="700" style="border:1px solid #d3d3d3;">
画布
</canvas>
<img src="" id="videoImage" width="350" height="700">
<button onclick="aphla()" style="height: 50px;width: 50px;">播放</button>
<button onclick="vdStop()" style="height: 50px;width: 50px;">暂停</button>
</body>
javascript var v = document.getElementById("myVideo");
var c = document.getElementById("myCanvas");
// var c = document.createElement("canvas");
var img = document.getElementById("videoImage");
ctx = c.getContext('2d');
var dataUrl;
const socket = new WebSocket('ws://xxxx.com:9502');
//Connection opened
socket.addEventListener('open', function (event) {
// socket.send('Hello Server! im websockt');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
img.src = event.data;
});
function playVideo() {
ctx.drawImage(v, 0, 0, 350, 700);
dataUrl = c.toDataURL("image/png");
// img.src = dataUrl;
socket.send(dataUrl);
}
var tick;
function aphla() {
tick = setInterval(function () {
playVideo();
}, 1);
}
function vdStop() {
clearInterval(tick);
}
用户页面
html<img src="" id="liveImg">javascript var img = document.getElementById("liveImg");
const socket = new WebSocket("ws://lm.com:9502");
//
socket.addEventListener('open',function(){
socket.send('Hello Server! Im live.html');
});
// Listen for messages
socket.addEventListener('message', function (event) {
//图片地址
img.src = event.data;
});
真直播应是通过rtmp推流实现的,本次功能仅作为swoole框架的一个案例用法
页:
[1]