聊天demo

本文分享了如何使用Signalr.js和uni-app框架构建一个简单的聊天应用。主要内容包括聊天页面布局设计,通过Signalr.js实现即时通讯,以及处理聊天记录和消息发送的细节。在进入聊天页面时,利用messageId和sessionId获取历史记录,并监听新消息。发送消息功能包括文本、表情的处理,以及时间显示策略。详细实现已封装在imTools.js中。
摘要由CSDN通过智能技术生成

太久没更新了好懒呀,之前做了一个聊天的app,今天分享一下。

聊天首先要有通讯录,然后会话列表,最后主要是聊天部分。板块太多,这里主要分享聊天内容,主要是Signalr.js来实现的,框架用了uni-app,做简易的app用uni-app真的是太香了。

首先我们先把页面大概格局准备好,这里主要包括内容区域{查看更多历史消息,行为消息,自己发出的消息,对方发出的消息},抽屉栏{表情包,更多功能-拍照、相册、转账等},底部输入栏{输入框,发送键,录音},具体布局就看个人爱好了。

然后是创建一个chart.js来连接我们的signalr.js,以及接收消息。

var Hub = require('@/common/wwwroot/lib/signalr/miniProgramSignalr.js')
import store from '@/store';
function hubStart(token){
	store.commit('$hubConnect', new Hub.HubConnection());
	store.state.hubConnect.start(store.state.websiteUrl+"/chatHub",{access_token:token});
	store.state.hubConnect.onOpen = res => {
	  console.log("成功开启连接");
	}
	//只管接受
	store.state.hubConnect.on("system", res => {
	  // uni.showToast("系统消息")
	})
	store.state.hubConnect.on("FriendRequestReceive", res => {
		let count=Number(store.state.hasNewFriend);
		count++;
		// console.log(count)
		store.commit('$hasNewFriend', count);
	});
}
function hubClose(){
	store.state.hubConnect.close({ reason: "退出" })
	store.commit('$hubConnect', null);
}


module.exports = {
	hubStart:hubStart,
	hubClose:hubClose
}

进入聊天页面会带进来一个messageId和sessionId(后端伙伴会给你的,sessionId:一个聊天室的id, messageId最新聊天内容的id),根据这两个id去获取当前聊天室的此前的聊天记录,如果此时有新消息接收,就可以根据sessionId是否相同来决定是否把该条新消息push到该聊天室的聊天框内。

onShow() {
			let _self = this;
			if(this.hubConnect&&this.hubConnect.openStatus){
				this.hubConnect.on("MessageReceive", res => {
					// console.log(res)
					_self.scrollToView ="";
					if(res.sessionId==_self.postData.sessionId){
						_self.screenMsg(res)
					}else{
						return
					}
				 });
			}else{
				setTimeout(function(){
					_self.hubConnect.on("MessageReceive", res => {
						// console.log(res)
						_self.scrollToView ="";
						if(res.sessionId==_self.postData.sessionId){
							_self.screenMsg(res)
						}else{
							return
						}
					 });
				},2000)
			}
			
			this.scrollTop = 9999999;
		},


// 接受消息(筛选处理)
			    screenMsg(msg) {
				let self = this;
				if(this.lastMessageId==msg.messageId){
					return false
				}
				this.lastMessageId=msg.messageId;
				this.setSingItem(msg,true,
				result=>{
					// self.msgList.push(result);
					self.$set(self.msgList,self.msgList.length,result)
					self.$nextTick(function(){
						self.scrollToView="";
						// console.log(self)
						self.scrollToView = "_"+result.messageId;
					})
					if(msg.contentType
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值