公众号实现即时聊天功能

为了在整个公众号中都能监听到聊天信息我这里将websocket相关功能放到了项目的App.vue文件中了

<script>
	export default {
		globalData: {
			req_header: uni.getStorageSync('token'),
			ws_url: 'wss://dtwy.eltyl.com:9999', //websocket连接地址
			ws_client: null, //websocket客户端连接实例
			ws_reLock: false, //websocket断线重连锁
			ws_timer_name: null, //websocket定时器名称
			ws_pant_fun: null //websocket心跳定时器
		},

		onLaunch: function() {
			let that = this;
			console.log('App Launch');
			that.websocket_init(); //websocket初始化
		},
		onShow: function() {
			console.log('App Show', );

		},
		onHide: function() {
			console.log('App Hide')
		},

		methods: {
			/**
			 * websocket初始化
			 */
			websocket_init: function() {
				var that = this;
				let token = uni.getStorageSync('token');
				let loginInfo = uni.getStorageSync('loginInfo');
				if (token) {
					that.globalData.ws_client = uni.connectSocket({
						url: that.globalData.ws_url + '?username=' + loginInfo.username + '&password=' + loginInfo.password,
						complete: () => {}
					});
					let ws_client = that.globalData.ws_client;
					if (ws_client != null) {
						//监听WebSocket连接打开事件
						ws_client.onOpen(function() {
							//console.log('ws连接成功');
							if (that.onOpen) {
								that.onOpen();
							}
							that.websocket_pant(); //心跳
						});
						//监听 WebSocket 接受到服务器的消息事件
						ws_client.onMessage(function(res) {
							//console.log(res);
							if (that.onMessage) {
								that.onMessage(res);
							}
						});
						//监听 WebSocket 连接关闭事件
						ws_client.onClose(function() {
							//console.log('ws关闭');
							if (that.onClose) {
								that.onClose();
							}
							that.websocket_re(); //websocket 断线重连
						});
						//监听 WebSocket 错误事件
						ws_client.onError(function() {
							//console.log('ws异常');
							if (that.onError) {
								that.onError();
							}
							that.websocket_re(); //websocket 断线重连
						});
					}
				}
			},

			/**
			 * websocket断线重连
			 */	
			websocket_re: function() {
				var that = this;
				//重连锁
				var ws_reLock = that.globalData.ws_reLock;
				if (ws_reLock == true) {
					return false;
				}
				//进行重连
				that.globalData.ws_reLock = true;
				let ws_client = that.globalData.ws_client;
				ws_client.close();
				let ws_timer_name = that.globalData.ws_timer_name;
				if (ws_timer_name != null) {
					//清除指定定时器
					clearTimeout(ws_timer_name);
				}
				that.globalData.ws_timer_name = setTimeout(function() {
					that.websocket_init();
					that.globalData.ws_reLock = false;
				}, 1000);
			},
			/**
			 * websocket心跳
			 */
			websocket_pant: function() {
				var that = this;
				clearInterval(that.globalData.ws_pant_fun);
				that.globalData.ws_pant_fun = setInterval(function() {
					that.globalData.ws_client.send({
						data: '{"type":"ping"}'
					});
				}, 50000);
			}
		}
	}
</script>

聊天界面直接使用

			//接收消息
			receive() {
				app.onMessage = (res => {
					let receiveData = JSON.parse(res.data)

					console.log(receiveData);
					if (receiveData.type == 'chat') {
						this.componentStatus = 'chat'
						if (receiveData.data.type == 2) {
							receiveData.data.content = JSON.parse(receiveData.data.content)
						}
						this.msgList.push(receiveData.data)
						this.rollingBottomTouch();
						console.log("sss", this.msgList)
					} else if (receiveData.type == 'video') {
						// this.componentStatus = 'video'

						if (receiveData.data.type == 0) {
							this.componentStatus = 'video_0'
							var mp3Url = "https://img.tukuppt.com/newpreview_music/08/98/71/5c88b2aa99cb94486.mp3";
							this.player = new Audio(mp3Url);
							this.player.loop = true;
							this.player.play(); //播放 mp3这个音频对象
						} else if (receiveData.data.type == -1) {
							this.componentStatus = 'chat'
						}
					}
				});
			}

上面对接收到的信息进行了判断是聊天信息还是视频聊天,如果是聊天信息就将其push到msgList方便遍历聊天数据

 发送消息实现

			//发送消息
			sending(data) {
				let that = this;
				// this.sendingData = sendingObj;
				app.globalData.ws_client.send({
					data: JSON.stringify(data)
				});
			},

因为websocke不太稳定,发送消息这边为保证消息的发送成功所以又用接口发了一遍信息

			chatmsgSave() {
				if (this.content == '') {
					uni.showToast({
						title: "请输入内容",
						icon: 'none'
					})
					return false;
				}
				let data = {
					fromId: uni.getStorageSync('user').id,
					fromName: uni.getStorageSync('user').realName,
					from_avatar: uni.getStorageSync('user').avatar,
					toId: this.doctorObj.id,
					toName: this.doctorObj.realName,
					toAvatar: this.doctorObj.avatar,
					type: this.type,
					content: this.content,
					orderNo: this.item.orderNo,
					userType: 5,
				}
				http({
					url: '/api/member/chatmsg/save',
					method: 'POST',
					data,
				}).then(res => {
					data['fromAvatar'] = data['from_avatar'];
					if (data.type == 1) {
						data['content'] = this.imgAllPath;
					}
					let msgObj = {
						type: "chat",
						data,
					}
					this.sending(msgObj)//这是websocket发送消息上面是接口发送
					this.msgList.push(data);
					this.rollingBottomTouch();
					this.content = '';

				})
			},

发送完后将发送的信息push到定义的聊天记录数组 msgList中方便遍历

实现效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值