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
 
 
posted @   偷甜瓜香喷喷  阅读(757)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示