vue+webSocket+springCloud消息推送交互(前后端代码教程)

主要讲解 vue+webSocket+springCloud消息推送交互项目实战;

话不多说,直接上代码;

一、后台代码:

1、pom里面加上依赖;

    
       <!--webSocket坐标依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.websocket</groupId>
            <artifactId>websocket-server</artifactId>
            <version>9.4.7.v20170914</version>
            <scope>test</scope>
        </dependency>

2、webSocket配置文件

/**
 * @description: webSocket配置类
 * @author: xgs
 * @date: 2020/2/11 11:14
 */
@Configuration
public class WebSocketConfig {
    /**
     * 注入ServerEndpointExporter,
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3、webSocket主类

package com.yzcx.project.service.webSocket;

import com.yzcx.common.constant.RedisKeyConstants;
import com.yzcx.onlinecar.util.RedisClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @description:
 * @author: xgs
 * @date: 2020/2/11 11:56
 */
@Component
@ServerEndpoint("/websocket/{userId}")
//此注解相当于设置访问URL
public class WebSocket {
    private static final Logger logger= LoggerFactory.getLogger(WebSocket.class);

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();


    /**
     * 开启连接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        logger.info("开启连接userId:{}",userId);
        this.session = session;
        //userID为空不连接
        if(StringUtils.isBlank(userId)){
            return;
        }
        if(sessionPool.get(userId)!=null){
            logger.info("此用户已存在:{}",userId);
            sessionPool.remove(userId);
        }
        webSockets.add(this);
        sessionPool.put(userId, session);
        logger.info("【websocket消息】有新的连接,总数为:{}",webSockets.size());
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】连接断开,总数为:{} this:{}",webSockets.size(),this);
    }

    /**
     * 接收消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客户端消息 message:{}",message);
    }

    /**
     * 异常处理
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }



    // 此为广播消息
    public void sendAllMessage(String string) {
        for(WebSocket webSocket : webSockets) {
           // logger.info("【websocket消息】广播消息:{}",string);
            try {
                webSocket.session.getAsyncRemote().sendText(string);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
                logger.info("【websocket消息】发送消息userId:{} message{}",userId,message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

4、使用场景:直接注入自己定义的 WebSocket ,用广播还是单点,自己直接用就行了;

5、注意点:

如果用了权限框架,记得加白名单  eg:  如果用的是springSecurity  需要在自定义的 SecurityConfig类中 antMatchers中加上 "/websocket/**";

如果用了nginx,还需要在nginx中加上配置;

location /xx_websocket {
            proxy_pass http://localhost:9106/接口前缀/websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            proxy_read_timeout 300s;         #webSocket默认断开时间是1分钟,这里改成5分钟,避免短时间内频繁重连
     }
 

二、前端代码

注意:由于没有前端开发来写前端,前端代码可能会显得比较粗暴,但是能用;

前端用的是vue,废话不多说,接着上代码;

data() {
    return {  
      websock: "", //webSocket使用
      isConnect: false, //webSocket连接标识 避免重复连接
      reConnectNum: 1, //断开后重新连接的次数 免得后台挂了,前端一直重连
    };
  },

  watch: {
   //监听用户信息,当登录了就有了这个用户ID,一开始他是空的
    "$store.getters.userId": function (newValue) {
      if (newValue) {
        //登录后有值了就去创建WebSocket连接
        if (newValue != null && newValue != "") {
          console.log("userId有值了,去连webSocket");
          this.initWebSocket();
          return;
        }
      }
    },
    //监听当前路由地址  this.$route.path https://blog.csdn.net/start_sea/article/details/122499868
    "$route.path": function (newValue) {
      if (newValue) {
        //曲线救国,指定一个路由名字,当点到这个路由的时候,如果webSocket没有连接,则主动去给他连接一次
        if (newValue == "给一个路由名") {
          if (!this.isConnect) {
            this.reConnectNum = 1;
            this.initWebSocket();
          }
        }
      }
    },
  },

  methods:{
    /*webSocket start*/
    initWebSocket() {
      console.log("进入initWebSocket");
      let userId = this.$store.getters.userId;
      console.log("系统用户ID:" + userId);
      if (userId != null && userId != "") {
        // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https

        //本地环境
       // let wsServer =
          `${
            location.protocol === "https" ? "wss" : "ws"
          }://localhost:9106/接口前缀/websocket/` + userId;

        //线上环境
        //webSocket 前面加一个前缀xxx_websocket_ 区分后面其他项目的webSocket
        let wsServer = "wss://域名地址或ip加端口/ nginx配置的  xxx_websocket/"+ userId;

        console.log("wsServer:", wsServer);
        this.websock = new WebSocket(wsServer);
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      }
    },
    websocketonopen() {
      console.log("WebSocket连接成功");
      //连接建立后修改标识
      this.isConnect = true;
    },
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
      //连接断开后修改标识
      this.isConnect = false;
      //连接错误 需要重连
      this.reConnect();
    },

    //接收后端推送过来的消息
    websocketonmessage(e) {
      //console.log(e)
      console.log("接收到后端传递过来的消息", e.data);
      if (e != null) {
        let str = JSON.parse(e.data);
         //todo 拿到消息了想干嘛就干嘛
      }
    },
    websocketclose(e) {
      //console.log("webSocket连接关闭:connection closed (" + e.code + ")");
      console.log("webSocket连接关闭");
      //连接断开后修改标识
      this.isConnect = false;
      this.websock='';
      this.reConnect();
    },

    reConnect() {
      console.log("尝试重新连接,本次重连次数:" + this.reConnectNum);
      if (this.reConnectNum > 6) {
        console.log("重连超过6次不再重连");
        return false;
      }
      //如果已经连上就不再重试了
      if (this.isConnect) return;
      this.initWebSocket();
      this.reConnectNum = this.reConnectNum + 1;
    },

  
    /*webSocket end*/
  
}

代码都写得这么清楚了,如果还是不会请留言,有更多的想法请留言,一起交流;

喜欢就关注,不定期还有干货!

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: Vue(前框架)和Spring Boot(后框架)结合起来实现websocket双工通信的步骤如下: 1. 首先,在Vue项目中安装`vue-native-websocket`插件。这个插件能够帮助我们在Vue中使用websocket。 2. 在Vue项目的根目录下创建一个文件,例如`webSocket.js`,在这个文件中,引入`vue-native-websocket`插件,并配置websocket服务的地址和口号。 3. 在Vue项目的入口文件(例如`main.js`)中,引入`webSocket.js`文件,并将websocket插件注册到Vue实例中。 4. 在Vue组件中,使用`this.$socket`来访问websocket对象。可以使用`this.$socket.send()`方法发消息给后。 5. 在Spring Boot项目中,添加`spring-boot-starter-websocket`的依赖。 6. 创建一个继承自`WebSocketConfigurer`接口的类,并实现其中的`registerWebSocketHandlers`方法。在该方法中,注册一个`WebSocketHandler`来处理前与后之间的websocket连接和消息传递逻辑。 7. 在`WebSocketHandler`中,重写`handleTextMessage`方法来处理接收到的文本消息。可以在这个方法中进行消息的处理逻辑,例如广播消息给所有连接的客户。 8. 在Spring Boot的配置类(例如`Application.java`)中,添加`@EnableWebSocket`来启用websocket支持。 9. 启动Spring Boot项目,并运行Vue项目。此时,前可以使用websocket连接到后,并进行双工通信。前可以通过`this.$socket.send()`方法发消息给后,后可以通过`WebSocketHandler`接收处理并响应消息给前。 以上就是使用Vue和Spring Boot来实现websocket双工通信的基本步骤。通过这种方式,前和后可以实时地进行双向通信,方便实现一些实时、聊天室等功能。 ### 回答2: Vue和Spring Boot结合实现WebSocket双工通信的步骤如下: 1. 在Vue项目中安装Vue-socket.io插件,可以在Vue项目的根目录下运行以下命令进行安装: ``` npm install --save vue-socket.io ``` 2. 在Vue项目的main.js文件中引入Vue-socket.io插件,并配置socket连接: ```javascript import VueSocketIO from 'vue-socket.io' import SocketIO from 'socket.io-client' Vue.use(new VueSocketIO({ debug: true, connection: SocketIO('http://localhost:8080'), // 这里的地址需要修改为后的IP地址和口号 })) ``` 3. 在Vue组件中使用WebSocket进行通信,例如,在Vue组件的created钩子中: ```javascript created() { this.$socket.emit('register', { userId: 123 }) // 发注册消息给后 this.$socket.on('message', (data) => { // 监听后消息 console.log('收到消息:', data) }) } ``` 4. 在Spring Boot中编写WebSocket控制器,处理前消息,并实现双工通信,例如: ```java @Controller public class WebSocketController { @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/register") public void registerUser(@Payload Map<String, Long> payload) { // 处理注册逻辑,例如保存用户ID等 Long userId = payload.get("userId"); // 广播消息给所有连接的用户 messagingTemplate.convertAndSend("/topic/message", "用户 " + userId + " 加入了聊天室"); } // 其他接口处理逻辑... } ``` 5. 在Spring Boot中配置WebSocket相关的bean,例如,在配置类中添加以下配置: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); // 消息代理前缀 registry.setApplicationDestinationPrefixes("/app"); // 应用消息前缀 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS(); } } ``` 以上是Vue和Spring Boot实现WebSocket双工通信的基本步骤,当前消息到后时,后可以处理并向所有连接的客户广播消息,实现实时的双工通信。 ### 回答3: Vue和Spring Boot均提供了支持WebSocket的功能,通过结合Vue和Spring Boot,我们可以实现WebSocket双工通信。 首先,在Vue项目中使用Vue提供的WebSocket API建立与后WebSocket连接,可以使用Vue的mounted生命周期钩子函数来实现这一步骤。通过WebSocket连接后,我们可以使用VueWebSocket对象来发数据给后,同时监听后的数据。 在后,我们使用Spring Boot提供的WebSocket支持来处理前的请求。首先,在Spring Boot的配置文件中,我们需要开启WebSocket功能。然后,我们可以通过创建一个WebSocketHandler类来处理前的请求和发消息给前。在WebSocketHandler中,我们可以实现OnOpen、OnMessage、OnClose等方法来处理前的连接、接收消息和关闭连接。在接收到消息后,我们可以编写相应的业务逻辑,如处理前的数据,然后将处理结果发给前。 通过上述步骤,我们实现了Vue和Spring Boot之间的WebSocket双工通信。前可以通过VueWebSocket对象与后进行实时的双向通信,后可以处理前的请求并发相应的消息给前。这使得实时的数据交互和通信成为可能,为应用程序添加了更多实时性和交互性。 需要注意的是,在实现WebSocket通信时,我们需要确保Vue和Spring Boot的版本兼容,并且正确配置相关的依赖和配置文件。同时,我们还需要考虑到安全性和性能等方面的因素,如认证和授权、连接数限制等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值