vue-cli使用sockjs即時通訊

  基於webSocket通訊的庫主要有 socket.ioSockJS,此次用的是 SockJS。vue

  這裏咱們使用sockjs-clientstomjs這兩個模塊,要實現webSocket通訊,須要後臺配合,也使用相應的模塊。git

一、sockjs-clientgithub

  sockjs-client是從SockJS中分離出來的用於客戶端使用的通訊模塊,因此咱們就直接來看看SockJS。SockJS是一個瀏覽器的JavaScript庫,它提供了一個相似於網絡的對象,SockJS提供了一個連貫的、跨瀏覽器的JavaScriptAPI,它在瀏覽器和Web服務器之間建立了一個低延遲、全雙工、跨域通訊通道。你可能會問,我爲何不直接用原生的WebSocket而要使用SockJS呢?這得益於SockJS的一大特性,一些瀏覽器中缺乏對WebSocket的支持,所以回退選項是必要的,而Spring框架提供了基於SockJS協議的透明的回退選項。SockJS提供了瀏覽器兼容性,優先使用原生的WebSocket,若是某個瀏覽器不支持WebSocket,SockJS會自動降級爲輪詢。web

二、stomjsvuex

  STOMP(Simple Text-Orientated Messaging Protocol) 面向消息的簡單文本協議,WebSocket是一個消息架構,不強制使用任何特定的消息協議,它依賴於應用層解釋消息的含義。與HTTP不一樣,WebSocket是處在TCP上很是薄的一層,會將字節流轉化爲文本/二進制消息,所以,對於實際應用來講,WebSocket的通訊形式層級太低,所以能夠在 WebSocket 之上使用STOMP協議,來爲瀏覽器 和 server間的通訊增長適當的消息語義。npm

  STOMP與WebSocket 的關係:跨域

  HTTP協議解決了web瀏覽器發起請求以及web服務器響應請求的細節,假設HTTP協議不存在,只能使用TCP套接字來編寫web應用,你可能認爲這是一件瘋狂的事情瀏覽器

  直接使用WebSocket(SockJS)就很相似於使用TCP套接字來編寫web應用,由於沒有高層協議,就須要咱們定義應用間發送消息的語義,還須要確保鏈接的兩端都能遵循這些語義;服務器

  同HTTP在TCP套接字上添加請求-響應模型層同樣,STOMP在WebSocket之上提供了一個基於幀的線路格式層,用來定義消息語義.websocket

三、代碼實現:

  先安裝 sockjs-client 和 stompjs

npm install sockjs-client npm install stompjs

  簡單代碼:

<script> import SockJS from 'sockjs-client' import Stomp from 'stompjs' import { mapGetters } from 'vuex' export default { data () { return { stompClient: '', timer: '', player: null, danmukuList: [{ 'mode': 1, 'text': '哈哈', 'stime': 1000, 'size': 25, 'color': 0xffffff }, { 'mode': 1, 'text': '前方高能', 'stime': 2000, 'size': 25, 'color': 0xff0000 }], barrageInfo: { text: '' } } }, computed: { ...mapGetters(['token']) }, methods: { // 阿里雲視頻直播
 aliPlay () { let src = 'https://live.enmotech.com/course/1.flv?auth_key=1554890972-0-0-2b26338fb5bc5d8e615ef9bf379c9914'
        this.player = new Aliplayer({ id: 'aliVedio', width: '100%', height: '100%', source: src, autoplay: true, isLive: false, rePlay: false, playsinline: true, preload: true, controlBarVisibility: 'hover', useH5Prism: true, components: [{ name: 'AliplayerDanmuComponent', type: AliPlayerComponent.AliplayerDanmuComponent, args: [this.danmukuList] }] }, function (player) { player._switchLevel = 0 }) }, // 鏈接後臺
 connection () { // 創建鏈接對象 // let sockUrl = 'https://' + window.location.host + '/event-websocket?token=' + this.token.substring(7)
        let sockUrl = 'https://csdev.enmotech.com/event-websocket?token=' + this.token.substring(7) let socket = new SockJS(sockUrl) // 獲取STOMP子協議的客戶端對象
        this.stompClient = Stomp.over(socket) // 定義客戶端的認證信息,按需求配置
        let headers = { Authorization: '' } // 向服務器發起websocket鏈接
        this.stompClient.connect(headers, () => { // 訂閱服務端提供的某個topic
          this.stompClient.subscribe('/topic/event', (msg) => { console.log('廣播成功') console.log(msg) // msg.body存放的是服務端發送給咱們的信息
 }) }, (err) => { // 鏈接發生錯誤時的處理函數
          console.log('失敗') console.log(err) }) }, // 斷開鏈接
 disconnect () { if (this.stompClient) { this.stompClient.disconnect() } }, // 初始化websocket
 initWebSocket () { this.connection() let that = this
        // 斷開重連機制,嘗試發送消息,捕獲異常發生時重連
        this.timer = setInterval(() => { try { that.stompClient.send('connect-test') } catch (err) { console.log('斷線了: ' + err) that.connection() } }, 5000) }, // 用戶加入發送彈幕
 sentBarrage () { let that = this
        this.danmukuList.push(this.barrageInfo) let headers = { Authorization: '' } this.stompClient.sent( '/topic/barrage', headers, JSON.stringify(that.barrageInfo) ) } }, mounted () { this.aliPlay() this.initWebSocket() }, beforeDestroy () { if (this.player) { this.player.dispose() this.player = null } // 頁面離開時斷開鏈接,清除定時器
      this.disconnect() clearInterval(this.timer) } } </script>
相關文章
相關標籤/搜索