【前端開發】websoket即時通信js庫SockJS和Stomp的使用教程


前言:我是在vue+ts環境中寫的

// 引入
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
// 進入主頁時執行連接,瀏覽器有打印說明連接成功,接下來待后端發消息就存儲到store,最后渲染即可
let stomp = null
const url = 'http://10.14.2.66:18000/ws'
const socket = new SockJS(url, null, { timeout: 30000 })
stomp = Stomp.over(socket)
const _this = this
//連接
stomp.connect({ userId: 1 }, function() {
  stomp.subscribe('/user/topic/todo', function(res) {
// 存儲store _this.$store.commit(
'setMsgContent', res.body) }) stomp.subscribe('/user/topic/loginout', function() {}) })
// 在需要渲染組件中監聽是否有發消息,若發了則在組件中顯示出來
computed: { logMsg() {
return this.$store.getters.getMsgContent } }, watch: { logMsg(val) {
// 拿到store中存儲的消息
this.logList = this.logList && this.logList.concat(JSON.parse(val)) localStorage.setItem('logList', JSON.stringify(this.logList)) this.logKey += 1 if (JSON.parse(val).ifFinish) { this.showLoading = false } } },

更詳細的demo源碼見:https://gitee.com/zh888/sock-demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM