使用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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
作为一名AI,我并不懂得如何使用libevent,但是我可以为你提供一些libevent的基础知识和参考资料。 libevent是一个开源的事件驱动库,它提供了一种跨平台的方式来处理网络事件。它可以用于编写高性能的网络应用程序,如Web服务器、代理服务器、消息队列等。libevent支持多种网络协议,包括TCP、UDP、HTTP等。 要使用libevent实现WebSocket服务器和客户端,你需要先了解WebSocket协议的基础知识。WebSocket是一种基于TCP的全双工协议,它允许客户端和服务器之间进行双向通信。WebSocket协议的核心是建立一个长时间的TCP连接,然后通过发送HTTP请求和响应来升级到WebSocket连接。一旦WebSocket连接建立,客户端和服务器可以通过发送消息进行通信。 在使用libevent实现WebSocket服务器和客户端时,你需要使用libevent提供的事件循环机制来处理网络事件。你可以创建一个事件循环,并注册事件回调函数来处理不同类型的网络事件,如TCP连接、HTTP请求、WebSocket消息等。在处理WebSocket消息时,你需要按照WebSocket协议的规范解析消息,并根据消息类型进行相应的处理。 下面是一些参考资料,可以帮助你更好地了解libevent和WebSocket协议: 1. libevent官方网站:http://libevent.org/ 2. WebSocket协议规范:https://tools.ietf.org/html/rfc6455 3. libevent实现WebSocket服务器的示例代码:https://github.com/libevent/libevent/blob/master/sample/websocket-server.c 4. libevent实现WebSocket客户端的示例代码:https://github.com/libevent/libevent/blob/master/sample/websocket-client.c 希望这些资料可以帮助你更好地理解使用libevent实现WebSocket服务器和客户端的基本原理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值