当前位置: 首页 > news >正文

WebSocket启用备忘

一:引入依赖:

<!--WebSocket专用--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.glassfish.tyrus.bundles</groupId><artifactId>tyrus-standalone-client</artifactId><version>2.1.5</version></dependency><!--WebSocket end-->

二:写Service:

@Component
@ServerEndpoint("/websocket/tterm")
public class WebSocketServerEterm {
@OnOpen
public void onOpen(Session session) {try {_socket = new Socket(serverIp, serverPort); // 使用配置中的IP和端口if (_socket.isConnected()) {。。。}
}}
@OnMessage
public void onMessage(String command, Session session) 
@OnClose
public void onClose(Session session) {try {if (_socket != null)_socket.close();System.out.println("Socket连接关闭: " + session.getId());} catch (IOException e) {System.err.println("关闭Socket资源失败:" + e.getMessage());}
}

 三、使用

const WS_BASE_URL = import.meta.env.VITE_WS_URL;
const url = WS_BASE_URL ? `${WS_BASE_URL}/websocket/tterm` : null;
 

// 切换模态框
const toggleEtermModal = async () => {if (!url) {message.error('WebSocket服务未配置');return;}etermVisible.value = !etermVisible.value;if (etermVisible.value) {try {await nextTick();document.querySelector('.eterm-input')?.focus();etermLoading.value = true;await etermApi.connect(url, {onMessage: (data) => {etermList.value.push({command: '',response: data});scrollToBottom();},onOpen: () => {socketConnected.value = true;etermList.value.push({command: '',response: '>>> 连接成功'});},onClose: () => {socketConnected.value = false;}});} catch (error) {message.error(`连接失败: ${error.message}`);etermVisible.value = false;} finally {etermLoading.value = false;}} else {etermApi.exit();}
};

四、正式环境需要结合NGINX:
 

# WebSocket 代理配置location /api/websocket/eterm {proxy_pass http://111.222.3.4:1111/websocket/eterm;# WebSocket 必须配置proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header Host $host;# 连接超时设置proxy_read_timeout 86400s;proxy_send_timeout 86400s;proxy_connect_timeout 5s;# 日志记录access_log /var/log/nginx/websocket.log websocket;}

相关文章:

  • Matlab 步进电机传递函数模糊pid
  • Yocto项目实战教程‑第6章‑Poky‑镜像菜谱‑机器配置文件‑发行版配置文件‑QEMU
  • 2025 第十六届蓝桥杯Java B组
  • 二进制枚举算法
  • 嵌入式学习——虚拟机通信
  • 零基础上手Python数据分析 (19):Matplotlib 高级图表定制 - 精雕细琢,让你的图表脱颖而出!
  • xss4之cookie操作
  • 前端知识深度学习
  • 认识MCP Function Calling AI Agent
  • 每日一题算法——链表相交
  • 21.Chromium指纹浏览器开发教程之触摸屏点指纹定制
  • Web前端:百度首页克隆 - 前端开发练习
  • 深入浅出 C++ 核心基础:从语法特性到入门体系构建
  • langchain-nextjs-template 模板安装与配置
  • 【深度学习—李宏毅教程笔记】各式各样的 Attention
  • jupyter切换存储路径
  • C++入门基础:引用,auto自动关键字,内联函数,范围for循环
  • 【C++】 —— 笔试刷题day_22
  • Postgresql几个常用的json操作
  • 安卓手机怎样配置数据加速
  • 特朗普:泽连斯基的言论对和平谈判非常有害
  • 云南大理州洱源县发生4.8级地震,震源深度10千米
  • 工程院院士应汉杰不再担任苏州大学校长
  • 中国全国政协-越南祖国阵线中央暨边境省份组织第三次友好交流活动在南宁开幕
  • 大连万达商业管理集团提前兑付“22大连万达MTN001” ,本息2.64亿元
  • 宇树的任务已经完成?王兴兴也在等待行业拐点