admin 发表于 2020-3-31 19:41:34

swoole 直播

主要使用 webstocket
上代码前端观看页面<script type="text/javascript">
var ws = new WebSocket('ws://192.168.0.150:9502');

ws.onopen = function() {
    console.log("连接成功");
};
ws.onmessage = function(e) {
   console.log(e);

   var data = e.data;
   document.getElementById('player').src=data;
};
ws.onerror = function() {
    console.log("关闭连接");
};
</script>录像页面
最好用火狐测试。<canvas id="output" style="display:none"></canvas>



<script type="text/javascript" charset="utf-8">


    var socket = new WebSocket('ws://192.168.0.150:9502');
    //socket.send("嗨我登陆了");

    var back = document.getElementById('output');
    var backcontext = back.getContext('2d');
    var video = document.getElementsByTagName('video');
   
    var success = function(stream){
      video.src = window.URL.createObjectURL(stream);
    }

    socket.onopen = function(){
      draw();
    }

    var draw = function(){
      try{
            backcontext.drawImage(video,0,0, back.width, back.height);
      }catch(e){
            if (e.name == "NS_ERROR_NOT_AVAILABLE") {
                return setTimeout(draw, 100);
            } else {
                throw e;
            }
      }
      if(video.src){
            socket.send(back.toDataURL("image/jpeg", 0.5));
      }
      setTimeout(draw, 100);
    }
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia || navigator.msGetUserMedia;
    navigator.getUserMedia({video:true, audio:false}, success, console.log);
</script> php

$server = new swoole_websocket_server("0.0.0.0", 9502);

$server->on('open', function (swoole_websocket_server $server, $request) {

    echo "新用户id:{$request->fd}加入了\n";
   // echo "server: handshake success with fd{$request->fd}\n";
});

$server->on('message', function (swoole_websocket_server $server, $frame) {

    //循环所有数据
    foreach($server->connections as $fd) {
      //返回数据
      $server->push($fd, $frame->data);
    }

});

$server->on('close', function ($ser, $fd) {
    echo "用户id: {$fd} 退出\n";
});

$server->start();











页: [1]
查看完整版本: swoole 直播