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;
        }
相关推荐
YuMiao2 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_5 天前
高可用移动网络连接
网络协议
chilix5 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP7 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅7 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19987 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205527 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel7 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)7 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~7 天前
Debian系统如何删除多余的kernel
linux·网络·debian