websocket播放rtsp方案之HTML实现

1前言

         之前本来想偷懒等前端哥们儿把代码写出来然后搞一下;但是由于各种原因还是没能等到(项目采用了其它方案);不过还是要感谢前端朋友的指教,太久没写了,js都不会写了;多谢前端哥们儿的代码;让该demo得以完整!

        不废话,上才艺!

2代码实现

controller


@Slf4j
@Controller
public class IndexController {
    @Autowired
    RTSPToImage RTSPToImage;

    @GetMapping("/test")
    public void test() {
        RTSPToImage.live();
        return;
    }

    @GetMapping("/")
    public String index() {
        RTSPToImage.live();
        return "index";
    }

}

html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<body>
<div>
    <img id="showVideo" src="">
</div>
<script src="../static/WebSocket.js" th:src="@{../WebSocket.js}"></script>

<script th:inline="javascript">
    var wsUrl = window.document.location.host + "/webSocket";
    //建立连接
    var ws1 = new Ws({
        host: "",
        port: "",
        path: wsUrl,
        wsMessageEvent: function (message) {
            //将接收到的二进制数据转为字符串
            var data = JSON.parse(message);
            if (data.code === 0) {
                console.log(message)
            } else if (data.code === 200) {
                document.getElementById("showVideo").setAttribute("src", "data:image/*;base64," + data.data)
            }
        }
    });

</script>
</body>

</html>

js

(function (window) {
    "use strict";
    let Event = {
        wsMessageEvent: function (message) {
            console.log(message)
        }
    }, dftOpt = {
        protocol: (window.location.protocol == 'http:') ? 'ws://' : 'wss://'
        , host: window.location.host
        , port: '80'
        , path: ''
        , isReConect: false
        , wsMessageEvent: Event.wsMessageEvent
    }, Util = {
        arrayLike(arrayLike) {
            Array.from(arrayLike)
        },
        isArray(arr) {
            Array.isArray(arr)
        },
        forEach(array, iterate) {
            let index = -1
                , length = array.length;
            if (typeof iterate != 'function') {
                return array;
            }
            while (++index < length) {
                iterate.call(array, array[index], index);
            }
        },
        isPlainObject(obj) {
            let flag = false;
            if (!obj || typeof obj != 'object') {
                return flag;
            }
            if (obj.constructor.prototype.hasOwnProperty("isPrototypeOf")) {
                flag = true;
            }
            return flag;
        },
        extend(...args) {
            if (args.length <= 0) {
                return
            };
            let target = args[0];
            if (args.length == 1) {
                return args[0]
            };
            this.forEach(args, (arg, i) => {
                if (i != 0) {
                    var keys = Object.keys(arg);
                    this.forEach(keys, (key, i) => {
                        var val = arg[key];
                        if (this.isPlainObject(val) || this.isArray(val)) {
                            var newTarget = this.isArray(val) ? [] : {};
                            target[key] = this.extend(newTarget, val);
                        } else {
                            target[key] = val;
                        }
                    });
                }
            });
            return target;
        }
    }, Ws = function (opt) {
        let config = this.config = Util.extend({}, dftOpt, opt);
        //接口地址url
        this.url = config.host === "" || config.host === "" ?
            config.protocol + config.path:
            config.protocol + config.host + ':' + config.port + config.path;
        //心跳状态  为false时不能执行操作 等待重连
        this.isHeartBeat = false;
        //重连状态  避免不间断的重连操作
        this.isReconnect = config.isReConect;
        //发送的消息
        this.curSendMes = null;
        //响应的信息
        this.message = null;
        //创建webSocket
        this.ws;
        //初始化websocket
        this.initWs = function () {
            //创建WebSocket
            let ws = this.ws = new WebSocket(this.url);
            // ws.binaryType = "arraybuffer";
            //Ws连接函数:服务器连接成功
            ws.onopen = (e) => {
                console.log(`与${this.config.host}:${this.config.port}${this.config.path}连接已建立...`)
                this.isHeartBeat = true;
                //发布事件
                this.send();
            };
            //Ws消息接收函数:服务器向前端推送消息时触发
            ws.onmessage = (e) => {
                //处理各种推送消
                this.message = e.data;
                config.wsMessageEvent.apply(this, [e.data]);
            }
            //Ws异常事件:Ws报错后触发
            ws.onerror = (e) => {
                this.isHeartBeat = false;
                this.reConnect();
            }
            //Ws关闭事件:Ws连接关闭后触发
            ws.onclose = (e) => {
                console.log('连接已关闭...');
                alert("websocket连接已关闭,按F5尝试重新刷新页面");
                this.isHeartBeat = false;
                ws = null;
                this.reConnect();
            };
        };
        this.initWs();
    };

    //重新连接
    Ws.prototype.reConnect = function () {
        //不需要重新连接,直接返回
        if (!this.isReconnect) return;
        this.isReconnect = true;
        //没连接上 会一直重连
        setTimeout(() => {
            this.initWs()
            this.isReconnect = false;
        }, 5000);
    }

    //发送消息
    Ws.prototype.send = function (content) {
        this.curSendMes = content || this.curSendMes;
        if(this.curSendMes == null){
            return;
        }
        if (this.isHeartBeat) {
            this.ws.send(this.curSendMes);
        }
    }
    window.Ws = Ws;
})(window);

 3测试验证

图片上有没有看见我帅气的脸,哈哈!到此希望摄像头相关的业务能告一段落。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值