主要代码如下,模拟器上面看没有问题,真机上有问题。
//app.js
const Realtime = require('./utils/realtime.js').Realtime;
App({
onLaunch: function () {
this.global.realtime = new Realtime({
appId: 'XStEpyoX0CIh6vTRzLsJB0Nv-gzGzoHsz',
region: 'cn',
noBinary: true,
pushOfflineMessages: false
});
},
global: {
realtime:null
}
});
//chat.js
var TextMessage = require('../../utils/realtime.js').TextMessage;
const convID = "585379221b69e60056ca2aa6";
var app = getApp();
var realtime = app.global.realtime;
var uname = "A";
Page({
onSend:function() {
console.log('onSend' + uname);
realtime.createIMClient(uname).then(function (user) {
return user.getConversation(convID);
}).then(function (conv) {
var data = {
type:1,
data:{
name:'yubo',
age:100
}
};
return conv.send(new TextMessage(JSON.stringify(data)));
}).then(function (message) {
console.log('send succ ' + JSON.stringify(message));
}).catch(console.error);
},
onRecv:function() {
console.log('onRecv' + uname);
realtime.createIMClient(uname).then(function(user) {
user.on('message', function(message, conversation) {
try {
var data = JSON.parse(message.text);
console.log('received: ' + data.type + " " + data.data.name + " " + data.data.age);
} catch (e) {
console.log('received: ' + message.text);
}
});
user.on('unreadmessages', function unreadMessagesEventHandler(payload, conversation) {
console.log(payload);
// {
// count: 4,
// lastMessageId: "UagNXHK0RHqIvM_VB7Injg",
// lastMessageTimestamp: [object Date],
// }
})
}).catch(console.error);
},
onMark:function() {
var CONV;
realtime.createIMClient(uname).then(function (user) {
return user.getConversation(convID);
}).then(function (conv) {
CONV = conv;
console.log("mark " + uname);
return conv.queryMessages({
'limit':10
});
}).then(function (messages) {
messages.forEach(function (message) {
try {
var data = JSON.parse(message.text);
console.log('query: ' + data);
} catch (e) {
console.log('query: ' + message.text);
}
});
CONV.markAsRead();
}).catch(console.error)
},
onOut:function() {
realtime.createIMClient(uname).then(function(user) {
return user.close();
}).then(function () {
console.log("close " + uname);
}).catch(console.error);
}
});