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

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

话不多说,直接上代码;

一、后台代码:

1、pom里面加上依赖;

    
       
        
            org.springframework.boot
            spring-boot-starter-websocket
            2.2.4.RELEASE
        
        
            org.eclipse.jetty.websocket
            websocket-server
            9.4.7.v20170914
            test
        

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 webSockets =new CopyOnWriteArraySet<>();
    private static Map sessionPool = new HashMap();


    /**
     * 开启连接
     * @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*/
  
}

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

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

你可能感兴趣的:(通信,java,websocket,vue.js)