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;
        }
相关推荐
DemonAvenger13 分钟前
Go中UDP编程:实战指南与使用场景
网络协议·架构·go
.YYY14 分钟前
网络--初级
网络·计算机网络
2501_9160074724 分钟前
iOS 性能测试工具全流程:主流工具实战对比与适用场景
websocket·tcp/ip·http·网络安全·https·udp
阿维的博客日记29 分钟前
HTTP/3.0的连接迁移使用连接ID来标识连接为什么可以做到连接不会中断
网络·网络协议·http
半路_出家ren33 分钟前
第8章:应用层协议HTTP、SDN软件定义网络、组播技术、QoS
网络·网络协议·http·mpls·qos·sdn软件定义网络·组播技术
teeeeeeemo1 小时前
http和https的区别
开发语言·网络·笔记·网络协议·http·https
Bruce_Liuxiaowei2 小时前
Netstat高级分析工具:Windows与Linux双系统兼容的精准筛查利器
linux·运维·网络·windows·安全
iFulling2 小时前
【计算机网络】第三章:数据链路层(下)
网络·笔记·计算机网络
Brookty2 小时前
【操作系统】进程(二)内存管理、通信
java·linux·服务器·网络·学习·java-ee·操作系统
易德研发2 小时前
ubuntu24.04安装NFS网络文件系统/ARM开发板NFS挂载
运维·服务器·网络