python读取监控流通过websocket连接发送到java服务端,服务端推流到前端

news/2024/5/9 14:45:06/文章来源:https://blog.csdn.net/weixin_44192389/article/details/132793858

在这里插入图片描述

  • python读取逐帧读取监控
import websocket
import base64
import cv2
import numpy as npvideoPath = "rtmp://ns8.indexforce.com/home/mystream"  // 此为公开RTSP流def on_message(ws, message):print(1)def connection_tmp(ws):websocket.enableTrace(True)ws = websocket.WebSocketApp("ws://127.0.0.1:8080/video",on_message=on_message,on_error=on_error,on_close=on_close)ws.on_open = on_opencap = cv2.VideoCapture(videoPath)try:ws.run_forever()except KeyboardInterrupt:ws.close()except:ws.close()def on_error(ws, error):reconnect_count=0print(type(error))print(error)print("正在尝试第%d次重连" % reconnect_count)reconnect_count += 1if reconnect_count < 100:connection_tmp(ws)def on_close(ws, close_status_code, close_msg):print("Connection closed:", close_status_code, close_msg)def on_open(ws):while cap.isOpened():ret, frame = cap.read()if not ret:breakencode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]result, imgencode = cv2.imencode('.jpg', frame, encode_param)data = np.array(imgencode)img = data.tostring()img = base64.b64encode(img).decode()try:ws.send("img=" + img)except websocket.WebSocketConnectionClosedException:print("WebSocket connection is closed. Cannot send data.")breakwebsocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://127.0.0.1:8080/video",on_message=on_message,on_error=on_error,on_close=on_close)ws.on_open = on_open
cap = cv2.VideoCapture(videoPath)
try:ws.run_forever()
except KeyboardInterrupt:ws.close()
  • Springboot集成websocket接收websocket连接请求
    pom文件添加配置
  <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><version>3.1.2</version></dependency><dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.3.5</version></dependency>

EnableWebsocket开启websocket

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
@EnableWebSocket
public class MyblogApplication {public static void main(String[] args) {SpringApplication.run(MyblogApplication.class, args);}}
package sxu.edu.hkj.myblog.config;//package sxu.edu.hkj.myblog.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import sxu.edu.hkj.myblog.controller.VideoWebSocketHandler;@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 在这里配置WebSocket处理程序并指定自定义端点路径registry.addHandler(new VideoWebSocketHandler(), "/video").setAllowedOrigins("*");}@Beanpublic ServletServerContainerFactoryBean createWebSocketContainer() {ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();// 在此处设置bufferSizecontainer.setMaxTextMessageBufferSize(1024000);container.setMaxBinaryMessageBufferSize(1024000);container.setMaxSessionIdleTimeout(15 * 60000L);return container;}}

通信服务:

package sxu.edu.hkj.myblog.controller;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.nio.ByteBuffer;@Component
public class VideoWebSocketHandler extends BinaryWebSocketHandler {private static final CopyOnWriteArraySet<WebSocketSession> SESSIONS = new CopyOnWriteArraySet<>();@Overridepublic void afterConnectionEstablished(WebSocketSession session) {SESSIONS.add(session);System.out.println("WebSocket消息】有新的连接,总数为:" + SESSIONS.size());}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) {SESSIONS.remove(session);System.out.println("【WebSocket消息】连接断开,总数为:" + SESSIONS.size());}@SneakyThrows@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message){// Handle incoming text messages here, if neededString textMessage = message.getPayload();
//        System.out.println("Received text message: " + textMessage);// Broadcast the received text message to all connected clientsfor (WebSocketSession clientSession : SESSIONS) {if (clientSession.isOpen() && !clientSession.equals(session)) {clientSession.sendMessage(new TextMessage(textMessage));}}}@Overrideprotected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws IOException {byte[] frameData = message.getPayload().array();System.out.println(frameData);// 将接收到的二进制图像数据发送给所有客户端for (WebSocketSession clientSession : SESSIONS) {try {if (clientSession.isOpen() && !clientSession.equals(session)) {// 创建一个新的BinaryMessage并发送给客户端BinaryMessage responseMessage = new BinaryMessage(ByteBuffer.wrap(frameData));clientSession.sendMessage(responseMessage);System.out.println("发送关闭广播++++++++++++++++++++++"+frameData);}} catch (IOException e) {e.printStackTrace();}}}
}

前端接收websocket广播信息,并绑定dom到前端

<imgclass="resizable-image11":src="image3Source"alt="Image"v-show="isCalibrating"style="opacity: 0.6; height: 560px; width: 1168px; margin:-569px -29px 12px -30.06px; pointer-events: none; filter: contrast(550%)"/>let ws = new WebSocket("ws://127.0.0.1:8082/video");ws.onopen = function(evt) {
};
ws.onopen = function (evt) {ws.send("Hello WebSockets!");isWebSocketConnected.value = true; // WebSocket is open
};ws.onclose = function (evt) {isWebSocketConnected.value = false; // WebSocket is closedvar reconnect_count=0reconnect_count += 1if (reconnect_count < 100){let ws = new WebSocket("ws://127.0.0.1:8082/video");}};ws.onmessage = function (event) {const message = event.data;const parts = message.split('=');const dataType = parts[0];const data = parts[1];if (dataType === 'img') {const imageData = 'data:image/jpeg;base64,' + data;document.getElementById('resImg').src = imageData;} else if (dataType === 'a1') {}
};ws.onclose = function(evt) {
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_358223.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

NLP(4)--BERT

目录 一、自监督学习 二、BERT的两个问题 三、GLUE 四、BERT与Transformer的关系 五、BERT的训练方式 六、BERT的四个例子 1、语句分类&#xff08;情感分析&#xff09; 2、词性标注 3、立场分析 4、问答系统 七、BERT的后续 1、为什么预训练后的微调可以满足多…

Python:安装Flask web框架hello world

安装easy_install pip install distribute 安装pip easy_install pip 安装 virtualenv pip install virtualenv 激活Flask pip install Flask 创建web页面demo.py from flask import Flask app Flask(__name__)app.route(/) def hello_world():return Hello World! 2023if _…

微信小程序上拉触底事件

一、什么是上拉触底事件 上拉触底是移动端的专有名词&#xff0c;通过手指在屏幕上的上拉滑动操作&#xff0c;从而加载更多数据的行为。 二、监听上拉触底事件 在页面的.js文件中&#xff0c;通过onReachBottom()函数即可监听当前页面的上拉触底事件。 三、配置上拉触底距…

使用perf_analyzer和model-analyzer测试tritonserver的模型性能超详细完整版

导读 当我们在使用tritonserver部署模型之后&#xff0c;通常需要测试一下模型的服务QPS的能力&#xff0c;也就是1s我们的模型能处理多少的请求&#xff0c;也被称为吞吐量。 测试tritonserver模型服务的QPS通常有两种方法&#xff0c;一种是使用perf_analyzer 来测试&#…

《React vs. Vue vs. Angular:2023年的全面比较》

&#x1f337;&#x1f341; 博主猫头虎 带您 Go to New World.✨&#x1f341; &#x1f984; 博客首页——猫头虎的博客&#x1f390; &#x1f433;《面试题大全专栏》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33a; &a…

SSM - Springboot - MyBatis-Plus 全栈体系(四)

第二章 SpringFramework 四、SpringIoC 实践和应用 1. SpringIoC / DI 实现步骤 1.1 配置元数据&#xff08;配置&#xff09; 配置元数据&#xff0c;既是编写交给SpringIoC容器管理组件的信息&#xff0c;配置方式有三种。基于 XML 的配置元数据的基本结构&#xff1a; …

基于堆叠⾃编码器的时间序列预测 深层神经网络

自适应迭代扩展卡尔曼滤波算法&#xff08;AIEK&#xff09;是一种滤波算法&#xff0c;其目的是通过迭代过程来逐渐适应不同的状态和环境&#xff0c;从而优化滤波效果。 该算法的基本思路是在每一步迭代过程中&#xff0c;根据所观测的数据和状态方程&#xff0c;对滤波器的…

13-RocketMQ主从同步(HA实现)源码原理

slave每次接收到master发过来的一批commitlog数据时&#xff0c;会看master传过来的这段commitlog的起始端&#xff0c;对应的全局物理偏移量&#xff0c;和slave本地存储的批commitlog数据的最大物理偏移量&#xff0c;是否相等 如果相等&#xff0c;也说明master端没有给sla…

系统架构设计专业技能 · 软件工程之UML建模设计

现在的一切都是为将来的梦想编织翅膀&#xff0c;让梦想在现实中展翅高飞。 Now everything is for the future of dream weaving wings, let the dream fly in reality. 点击进入系列文章目录 系统架构设计高级技能 软件工程之UML建模设计 一、需求分析 - UML图二、用例图2.…

十五、Webpack打包图片-js-Vue、Label命令、resolve模块解析

一、webpack打包图片 &#xff08;1&#xff09;加载图片案例准备 为了演示我们项目中可以加载图片&#xff0c;我们需要在项目中使用图片&#xff0c;比较常见的使用图片的方式是两种&#xff1a; img元素&#xff0c;设置src属性&#xff1b;其他元素&#xff08;比如div&…

【GAMES202】Real-Time Ray Tracing 1—实时光线追踪1

一、前言 这篇我们开始新的话题—Real-Time Ray Tracing简称RTRT&#xff0c;也就是实时光线追踪&#xff0c;关于光线追踪&#xff0c;我们已经不止一次提到过它的优点&#xff0c;无论是软阴影还是全局光照&#xff0c;光线追踪都很容易做&#xff0c;唯一的缺点就是速度太慢…

【新版】系统架构设计师 - 软件架构设计<SOA与微服务>

个人总结&#xff0c;仅供参考&#xff0c;欢迎加好友一起讨论 架构 - 软件架构设计&#xff1c;SOA与微服务&#xff1e; 考点摘要 面向服务SOA&#xff08;★★★★&#xff09;微服务&#xff08;★★★★&#xff09; 基于/面向服务的&#xff08;SOA&#xff09; 在SO…

Ubuntu23.10将推出全磁盘加密功能,提高系统安全性

Canonical 宣布其即将推出的 Ubuntu 23.10&#xff08;Mantic Minotaur&#xff09;将引入基于 TPM 的全磁盘加密的初步支持。这个特性将利用系统可信平台模块&#xff08;TPM&#xff09;&#xff0c;在系统级别上进行全磁盘加密&#xff0c;从而提高系统的安全性。 但需要注…

布局过程的完全解析

前言 那么为什么要分为两个流程呢 因为测量流程是一个复杂的流程&#xff0c;有时候不一定一遍就能得出测量结果&#xff0c;可能需要 2 - 3 次甚至更多 自定义布局的几种类型&#xff0c;也是自定义布局的两个方法 实战&#xff0c;第一种类型&#xff1a;改写已有View 的步骤…

Unity中Shader抓取屏幕并实现扭曲效果

文章目录 前言一、屏幕抓取&#xff0c;在上一篇文章已经写了二、实现抓取后的屏幕扭曲实现思路&#xff1a;1、屏幕扭曲要借助传入 UV 贴图进行扭曲2、传入贴图后在顶点着色器的输入参数处&#xff0c;传入一个 float2 uv : TEXCOORD&#xff0c;用于之后对扭曲贴图进行采样3、…

SQL Server2022安装教程

SQL Server 是一个关系数据库管理系统。它最初是由Microsoft、Sybase 和Ashton-Tate三家公司共同开发的&#xff0c;于1988 年推出了第一个OS/2版本。在Windows NT 推出后&#xff0c;Microsoft与Sybase 在SQL Server 的开发上就分道扬镳了&#xff0c;Microsoft 将SQL Server移…

mac电脑安装paste教程以及重新安装软件后不能使用解决方法

问题背景 mac电脑安装paste教程以及重新安装软件后不能使用解决方法。 mac电脑安装paste失败&#xff0c;安装好后还是无法使用&#xff0c;paste显示还是历史粘贴信息&#xff0c;导致无法使用。新 copy的内容也无法进入历史粘贴版里面。 笔者电脑配置信息&#xff1a;MacB…

GLSL ES着色器 精度限定字

目录 前言 WebGL支持的三种精度 数据类型的默认精度 float类型没有默认精度 预处理指令 在GLSL ES中常用的三种预处理指令。 预定义的内置宏 前言 GLSL ES新引入了精度限定字&#xff0c;目的是帮助着色器程序提高运行效率&#xff0c;削减内存开支。顾名思义&#xf…

Linux C : select简介和epoll 实现

目录 一、基础知识 二、select 模型服务流程 二、select 模式的缺点。 三、poll 概要 四、epoll 服务端实现流程 1.epoll_create&#xff1a; 2.epoll_ctl 3.epoll_wait 五、epoll示例代码实现 1.epoll实现服务端 2.客户端采用tcp进行访问 一、基础知识 首先要知道&…

wpf C# 用USB虚拟串口最高速下载大文件 每包400万字节 平均0.7s/M,支持批量多设备同时下载。自动识别串口。源码示例可自由定制。

C# 用USB虚拟串口下载大文件 每包400万字节 平均0.7s/M。支持批量多设备同时下载。自动识别串口。可自由定制。 int 32位有符号整数 -2147483648~2147483647 但500万字节时 write时报端口IO异常。可能是驱动限制的。 之前用这个助手发文件&#xff0c;连续发送&#xff0…