swoole视频直播(记录用 未测试)
服务器代码$serv=new swoole_websocket_server("0.0.0.0",9501);
$client=array();
$serv->on("open",function($serv,$req)use($client){
//echo 'connect'.$req->fd;
$client[]=$req;
//var_dump($client);
$serv->push($req->fd,'aa');
});
$serv->on("message",function($serv,$frame)use ($client){
/*var_dump($frame->data);
foreach($client as $key =>$val){
$serv->push($val->fd,'aa');
}*/
$client=$serv->connection_list();
var_dump($client);
foreach($client as $key =>$val){
if($val!=$frame->fd){
$serv->push($val,$frame->data);
}
}
});
$serv->on("close",function($serv,$fd){
echo 'close';
});
$serv->start();
主播客户端
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>404</title>
<style>
body{
background-color:#444;
font-size:14px;
}
h3{
font-size:60px;
color:#eee;
text-align:center;
padding-top:30px;
font-weight:normal;
}
</style>
</head>
<body>
<video src="test.mp4" width="400" id="video" autoplay="true" controls="true"></video>
<canvas width="400" id="canvas" height="400" style="display:none"></canvas>
<canvas width="400" id="canvas2" height="400" ></canvas>
<script>
var video=document.getElementById('video');
var canvas=document.getElementById('canvas');
var canvas2=document.getElementById('canvas2');
var context=canvas.getContext('2d');
var context2=canvas2.getContext('2d');
function draw(){
context.drawImage(video,0,0,400,400);
ws.send(canvas.toDataURL('image/jpeg',0.8));
setTimeout(draw,800);
}
//客户端跟服务端通讯
if (window.MozWebSocket)
{
ws = new MozWebSocket("ws://182.61.42.187:9501");
} else
{
ws = new WebSocket("ws://182.61.42.187:9501");
}
ws.onopen=function(event){
alert('连接成功');
ws.binaryType = 'arraybuffer';
draw();
}
ws.onmessage=function(event){
//alert(event.data);
//ws.send(event.data+"client");
qrCodeImg = new Image();
qrCodeImg.src = event.data;
context2.drawImage(qrCodeImg, 0, 0, 400, 400);
}
ws.onclose=function(event){
alert('close');
}
ws.onerror=function(event){
alert('error');
}
//video,标签模拟视频
</script>
</body>
</html>
客户端:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>客户端直播页面</title>
</head>
<body>
<img id="receiver" style="width:720px;height:480px">
<script type="text/javascript" charset="utf-8">
var receiver_socket = new WebSocket("ws://182.61.42.187:9501");
var image = document.getElementById('receiver');
receiver_socket.onmessage = function(data) {
console.log(data.data);
image.src = data.data;
}
</script>
</body>
</html>
页:
[1]