leancloud 即时消息通讯

leancloud这个框架我也是第一次接触,碰到的问题也挺多的。我是基于VUE做的,很多方法也都进行了一个基础性的封装,我也不是什么大神,欢迎吐槽。首先是解决一个通信的问题,也就是发送消息。

1、引入相关的东西(都是按官网上来的),appId和appKey是需要自己去申请的,具体看官网上怎么操作的。

import Vue from 'vue'
let AV = require('leancloud-storage');
AV.init({
appId: appId,
appKey: appKey
});
let {
Realtime,
TextMessage,
ImageMessage
} = require('leancloud-realtime');
let realtime = new Realtime({
appId: appId,
pushOfflineMessages: true,
region: 'cn', // 美国节点为 "us"
})

2.发送消息

/* 发送消息 */
Vue.prototype.sendMsg = function(formNmae, toName, msg, ) {
realtime.createIMClient(formNmae).then(function(tom) {
// 创建对话
return tom.createConversation({
members: [toName],
name: toName + '&' + formNmae,
});
}).then(function(conversation) {

//发送成功之后,页面是需要渲染历史消息的
conversation.queryMessages({
limit: 10, // limit 取值范围 1~1000,默认 20
}).then(function(messages) {
console.log(messages)
}).catch(console.error.bind(console));
return conversation.send(new TextMessage(msg));
}).catch(console.error);
}

3.接收消息,需要有对应的人,也就是对应的会话概念。

/* 接收消息 */
Vue.prototype.getMsg = function(toName) {
realtime.createIMClient(toName).then(function(jerry) {
jerry.on('message', function(message, conversation) {
console.log('Message received: ' + message.text);
})
})
}

4.怎么样拿到一个会话的历史消息,我还在研究。官方是有一个介绍。

a.根据消息类型查询

conversation.queryMessages({ type: ImageMessage.TYPE }).then(messages => {

 console.log(messages); }).catch(console.error);

b.查询历史消息

curl -X GET \
  -H "X-LC-Id: 8yBVbIHUTbs6jdM1TriACisQ-gzGzoHsz" \ -H "X-LC-Key: Okdkx1JRoCGE3s0k56hhvMqM,master" \ -H "Content-Type: application/json" \ https://8ybvbihu.api.lncld.net/1.2/rtm/conversations/{conv_id}/messages
 
 

猜你喜欢

转载自www.cnblogs.com/ruose/p/10076339.html