springboot+vue 使用websocket后臺主動向前臺推送消息

前提

     本篇文章適用于入門級別,不做深入研究。

后臺springboot代碼

引入依賴

        <!--websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

配置類

@Configuration
public class CommonConfig {

    /**
     * websocket配置
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

websocket服務類

@ServerEndpoint("/websocket/{username}")
@Slf4j
@Component
public class Websocket {
    //靜態(tài)變量,用來記錄當前在線連接數(shù)。設計為安全的
    private static int onlineCount = 0;
    //concurrentHashMap分段鎖,用來存放每個客戶端對應的Websocket對象。
    private static Map<String, Websocket> clients = new ConcurrentHashMap<String, Websocket>();
    //與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)
    private Session session;
    private String username;

    /**
     * 連接建立成功調(diào)用的方法
     * @param username
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        this.username = username;
        this.session = session;
        Websocket.onlineCount++;
        log.info("有一連接進入!當前在線人數(shù)為" + onlineCount);
        clients.put(username, this);
    }

    /**
     * 連接關(guān)閉調(diào)用的方法
     */
    @OnClose
    public void onClose() {
        clients.remove(username);
        Websocket.onlineCount--;
        log.info("有一連接關(guān)閉!當前在線人數(shù)為" + onlineCount);

    }

    /**
     * 收到客戶端消息后調(diào)用的方法
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到客戶端的消息"+message);
        sendMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket發(fā)生錯誤:" + throwable.getMessage());
    }

    public static void sendMessage(String message) {
        // 向所有連接websocket的客戶端發(fā)送消息
        // 可以修改為對某個客戶端發(fā)消息
        for (Websocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }
}

測試請求方法

@RestController
@RequestMapping("/news")
public class NewsController {

    @GetMapping("/send")
    public String send(){
        Websocket.sendMessage("這是websocket群發(fā)消息!");
        return "發(fā)送消息成功";
    }

}

前端VUE

這是在創(chuàng)建vue項目自帶的HelloWorld.vue文件里修改的

<template>
  <div class="hello">
    <h1>測試webSocket</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },

  created() { // 頁面創(chuàng)建生命周期函數(shù)
    this.initWebSocket()
  },
  destroyed: function () { // 離開頁面生命周期函數(shù)
    this.websocketclose();
  },
  methods: {
    initWebSocket: function () {
      // WebSocket與普通的請求所用協(xié)議有所不同,ws等同于http,wss等同于https
      this.websock = new WebSocket("ws://127.0.0.1:8031/websocket/test");
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen: function () {
      console.log("WebSocket連接成功");
    },
    websocketonerror: function () {
      console.log("WebSocket連接發(fā)生錯誤");
    },
    websocketonmessage: function (e) {
      console.log(e.data);                // console.log(e);
    },
    websocketclose: function (e) {
      console.log("connection closed (" + e.code + ")");
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

測試

OK!代碼部分已結(jié)束,現(xiàn)在先啟動后臺springboot,和前端vue。打開頁面按下F12看日志打印。


image.png

非常好,這時候說明前后端websocket已經(jīng)連接成功了。
下面用你的工具(http測試工具,postman之類的)測試推送消息接口。

image.png

很棒,調(diào)用接口成功,信息成功發(fā)送。下面看看前端是否收到。

image.png

OK!大功告成!各位朋友!
good luck!
后會有期!

有什么問題也可以私信我或評論,看到就會回復。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容