欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

websocket直播

程序员文章站 2022-04-10 17:10:03
...
1.websocket转发的最简单server
2.h5接收websocket数据,写到img里
3.h5获取摄像头,并send到另一端

server代码:
sendserver.js
var express = require('express'),
app = express(),
server = require('http').createServer(app);

server.listen(3000);
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/send.html');
    res.sendfile(__dirname + '/receive.html');
});

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({server: server});

// 存储socket的数组,这里只能有2个socket,每次测试需要重启,否则会出错
var wsc = [],
index = 1;
// 有socket连入
wss.on('connection', function(ws) {
    console.log('connection');
    // 将socket存入数组
    wsc.push(ws);
    // 记下对方socket在数组中的下标,因为这个测试程序只允许2个socket
    // 所以第一个连入的socket存入0,第二个连入的就是存入1
    // otherIndex就反着来,第一个socket的otherIndex下标为1,第二个socket的otherIndex下标为0
    var otherIndex = index--,
    desc = null;

    if (otherIndex == 1) {
        desc = 'first socket';
    } else {
        desc = 'second socket';
    }
    // 转发收到的消息
    ws.on('message', function(message) {
        wsc[otherIndex].send(message, function (error) {
            if (error) {
                console.log('Send message error (' + desc + '): ', error);
            }
        });
    });
});


接收端代码:
receive.html
<img id="receiver" style="width:1600px;height:900px"/>
<script type="text/javascript" charset="utf-8">
        //创建一个socket实例
        var receiver_socket = new WebSocket("ws://localhost:3000");
        alert("ws://"+document.domain+":3000")
        var image = document.getElementById('receiver');
         // 监听消息
        receiver_socket.onmessage = function(data)
        {
            console.log("onmessage");
            image.src=data.data;
        }
</script>

发送端代码:
send.html

~
~
~
<video autoplay id="sourcevid" style="width:1600;height:900px"></video>

<canvas id="output" style="display:none"></canvas>^@<script type="text/javascript" charset="utf-8">
        //创建一个+实例
        var socket = new WebSocket("ws://localhost:3000");
        var back = document.getElementById('output');
        //返回一个用于在画布上绘图的环境。
        var backcontext = back.getContext('2d');
        var video = document.getElementsByTagName('video')[0];
        var success = function(stream){
            //获取视屏流,转换为url
            //video.src = window.URL.createObjectURL(stream);
            video.srcObject = stream;
        }
        //打开socket
        socket.onopen = function(){
            draw();
            console.log("open success")
        }
        // 将视频帧绘制到Canvas对象上,Canvas每100ms切换帧,形成肉眼视频效果
        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, 10);
                } else {
                    throw e;
                }
            }
            if(video.srcObject){
                // Canvas的内容转化成PNG data URI并发送到服务器,0.5为和压缩系数
                socket.send(back.toDataURL("image/jpeg", 0.5));
            }
            setTimeout(draw, 10);
        }
        //调用设备的摄像头,并将资源放入video标签
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia || navigator.msGetUserMedia;
        navigator.getUserMedia({video:true, audio:false}, success, console.log);
    </script>

相关标签: websocket