Vite+Vue根据环境配置Websocket地址

  • Vite+Vue根据环境配置Websocket地址已关闭评论
  • 72 次浏览
  • A+
所属分类:Web前端
摘要

上回说到,利用vite加载不同mode下的配置文件,可以实现不同运行环境下的参数配置。在前端应用中经常使用到Websocket,其地址同样可以在.env中间中配置。


前言

上回说到,利用vite加载不同mode下的配置文件,可以实现不同运行环境下的参数配置。在前端应用中经常使用到Websocket,其地址同样可以在.env中间中配置。

代码

vite.config.ts代码的执行是在createApp之前,不可以在vite.config.ts中使用例如piniarouter等组件。可以使用import.meta.env获取配置文件中的参数

废话少说,直接上代码。

前端

.env.development

# 开发环境配置 NODE_ENV='development'  # 本地服务端口 VITE_PORT=8093  .......  # Websocket服务地址 VITE_WS_URL='ws://localhost:8083' 

demo.vue

const wsPath = import.meta.env.VITE_WS_URL + 'ws/demo'; let wsSocket: any; function wsInit() {   if (typeof (WebSocket) === 'undefined') {     console.log("浏览器不支持websocket");   } else {     wsSocket = new WebSocket(wsPath);     wsSocket.onopen = open;     wsSocket.onerror = error;     wsSocket.onmessage = getMessage;   } } function open() {   console.log("websocket连接成功") }  function error(error: string) {   console.log("websocket连接错误", error) } function getMessage(msg: MessageEvent) {   let states = msg.data;   states = JSON.parse(states);   states.forEach((dataItem: any) => {    }); } function send(params: string) {   wsSocket.send(params) }  function close(e: any) {   console.log("websocket连接关闭") } onMounted(() => {   wsInit(); }) onUnmounted(() => {   wsSocket.onclose = close; }) 

后端

Websocket.config.java

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter;  @Configuration public class WebSocketConfig {     @Bean     public ServerEndpointExporter serverEndpointExporter(){         return new ServerEndpointExporter();     } } 

DemoWebsocketServer.java

import io.micrometer.common.util.StringUtils; import jakarta.websocket.*; import jakarta.websocket.server.ServerEndpoint; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component;  import java.io.IOException; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap;  @Slf4j @Component @ServerEndpoint(value = "/ws/demo") public class DemoWebsocketServer {     private static ConcurrentHashMap<String, DemoWebsocketServer> webSocketMap = new ConcurrentHashMap<>();     @Getter     private Session session;      public String pointsUrl;     private static StringRedisTemplate stringRedisTemplate;      @Autowired     public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {         DemoWebsocketServer.stringRedisTemplate = stringRedisTemplate;     }      /**      * 连接建立成功调用的方法      */     @OnOpen     public void onOpen(Session session) {         this.session = session;         log.info("{}连接成功", this.getSession());         webSocketMap.put(session.getId(), this);         sendMessage("");     }      @OnMessage     public void onMessage(String message) {         // todo 获取前端发送过来的     }      /**      * 连接关闭调用的方法      */     @OnClose     public void onClose() {         //从set中删除         webSocketMap.remove(this.getSession().getId());         log.info("断开连接" + this.getSession());     }      /**      * @param error      */     @OnError     public void onError(Throwable error) {         if (error.getMessage().contains("Broken pipe")) {             log.info("客户端突然断开连接");         } else {             System.out.println("发生错误");             error.printStackTrace();         }     }      /**      * 实现服务器主动推送      */     public void sendMessage(String message) {         synchronized (webSocketMap) {             if (!StringUtils.isEmpty(this.getSession().getId()) && webSocketMap.containsKey(this.getSession()                     .getId())) {                 try {                     webSocketMap.get(this.getSession().getId()).getSession().getBasicRemote().sendText(message);                 } catch (IOException e) {                     throw new RuntimeException(e);                 }             }         }     }      @Override     public boolean equals(Object o) {         if (this == o) {             return true;         }         if (o == null || getClass() != o.getClass()) {             return false;         }         DemoWebsocketServer that = (DemoWebsocketServer) o;         return Objects.equals(session, that.session) && Objects.equals(pointsUrl, that.pointsUrl);     }      @Override     public int hashCode() {         return Objects.hash(session, pointsUrl);     } }