使用SockJS和StompJS实现WebSocket订阅服务

一、首先用npm安装 socketJS 和 stompJS

npm install sockjs-client
npm install stompjs

二、在页面中引入这2个js

import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

三、初始化websocket连接,定义一个对象(socketClient)接收订阅服务的实例化

// 初始化ws连接
initSocketConnection () {
    
    
    const _url = 'Your Websocket Url'
    const _socket = new SockJS(_url)
    this.socketClient = Stomp.over(_socket)
	// 向服务器发起websocket连接并发送CONNECT帧
	this.socketClient.connect(
		{
    
     login: '', passcode: '' },
		// 连接成功的回调函数
		function connectCallback (success) {
    
    
			console.log('webSocket连接成功:', success)
		},
		// 连接失败时的回调函数
		function errorCallBack (error) {
    
    
			console.log('webSocket连接失败:', error)
		}
	)
}

四、开始订阅(如需多个订阅频道,可以用一个变量monitorList)

// 点击开始订阅按钮
onStartMonitor () {
    
    
	// 多个订阅频道时找出当前激活的频道
    const _activeRoom = this.monitorList.find(item => item.name === this.activeMonitorTabName)
    _activeRoom.isPaused = false
    this.startChatRoom()
},

// 点击暂停订阅按钮
onPauseMonitor () {
    
    
	// 多个订阅频道时找出当前激活的频道
    const _activeRoom = this.monitorList.find(item => item.name === this.activeMonitorTabName)
    _activeRoom.isPaused = true
    this.pauseChatRoom()
},

// 执行开始订阅
startChatRoom () {
    
    
	// 找出当前激活的频道
    const _activeRoom = this.monitorList.find(item => item.name === this.activeMonitorTabName)
    // 自己定义查询的参数
    const params = {
    
    
        'chatRoomId': _activeRoom.chatRoomId,
    }
    // 转换格式为base64,也可以不转,看你的服务器需求
    const query = window.btoa(JSON.stringify(params))
    // 为当前频道增加订阅服务
    _activeRoom.subscribe = this.socketClient.subscribe(`/client/roomChat/?jsonStr=${
      
      query}`, (message) => {
    
    
    	// 可以看看message里面的东西,取出想要的即可
        const _result = JSON.parse(message.body)
        if (_result.data.chatLogs && _result.data.chatLogs.length > 0) {
    
    
            const _chatData = _result.data.chatLogs
            _activeRoom.tableData = _chatData.concat(_activeRoom.tableData)
        }
    })
},

// 暂停订阅
pauseChatRoom (name) {
    
    
    let _activeRoom = this.monitorList.find(item => item.name === this.activeMonitorTabName)
    if (name) {
    
    
        _activeRoom = this.monitorList.find(item => item.name === name)
    }
    if (_activeRoom.subscribe) {
    
    
        _activeRoom.subscribe.unsubscribe()
    }
},

// 销毁ws连接
disconnect () {
    
    
    if (this.socketClient) {
    
    
        this.socketClient.disconnect()
    }
},

// vue生命周期,离开或关闭页面时销毁ws连接
beforeDestroy () {
    
    
	this.disconnect()
},

五、增加订阅频道功能

// 增加频道
onAddMonitor () {
    
    
    if (this.monitorList.length >= 10) {
    
    
        return this.$Message.error('最多只能添加10个频道')
    }
    // 使用一个计数器来标记唯一的频道id
    this.counter++
    const _obj = {
    
     ...this.monitorTemplate }
    _obj.id = new Date().getTime()
    _obj.name = _obj.name + '_' + _obj.id
    _obj.chatRoomId = this.counter + '_1'
    this.monitorList.push(_obj)
    if (this.monitorList.length === 1) {
    
    
        this.activeMonitorTabName = this.monitorList[0].name
    }
},

六、所需要的data数据

data() {
    
    
	return {
    
    
		monitorList: [],
		monitorTemplate: {
    
    
			id: null,
            label: '频道',
            name: 'monitorTab',
            chatRoomId: '',
            isPaused: true,
            subscribe: null,
            tableData: [],
		},
		activeMonitorTabName: '',
		socketClient: null,
	}
}

相关网站:
sockjs

https://github.com/sockjs/sockjs-node

stomp-websocket

https://github.com/jmesnil/stomp-websocket

猜你喜欢

转载自blog.csdn.net/xjtarzan/article/details/121125054
今日推荐