微信小程序特别提醒:
如果需要在小程序里使用IM聊天,需要登录微信公众平台->微信小程序开发设置->服务器域名, 添加socket合法域名:wss://wx-hangzhou.goeasy.io
var options = {
host:'hangzhou.goeasy.io', //应用所在的区域地址: [hangzhou.goeasy.io, 新加坡暂不支持IM,敬请期待]
appkey: "my_appkey" //common key
}
//初始化
var im = GoEasyIM.getInstance(options);
var user = {
id:'user001', //当前用户的唯一标识符
data:'{"avatar":"/www/xxx.png","nickname":"Neo"}' //当前用户的扩展数据, 任意格式的字符串或者对象,用于会话列表conversation.data和群消息的senderData
}
//连接GoEasy
var promise = im.connect(user);
promise.then(function() {
console.log("Connection successful.");
}).catch(function(error) {
console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
});
//创建消息, 内容最长不超过3K,可以发送字符串,对象和json格式字符串
let textMessage = im.createTextMessage({
text:'Hello, GoEasyIM', //消息内容
to : {
type : GoEasyIM.SCENE.PRIVATE, //私聊还是群聊,群聊为GoEasyIM.SCENE.GROUP
id : 'user002',
data:'{"avatar":"/www/xxx.png","nickname":"Neo"}' //好友扩展数据, 任意格式的字符串或者对象,用于更新会话列表conversation.data
}
});
//发送消息
var promise = im.sendMessage(textMessage);
promise.then(function(message) {
console.log("Private message sent successfully.", message);
}).catch(function(error) {
console.log("Failed to send private message,code:" + error.code +",error"+error.content);
});
对于收到且已读的消息,需要标记为已读状态,否则会话列表里的数字始终保持原来数字,并且在下次连接GoEasy时,GoEasy会重复下发之前未标记的消息。
var onPrivateMessageReceived = function(message) {
//文字消息
// {
// "messageId": "8f0e27a0c7e111eab347b726da4416bd",
// "timestamp": 1594958217087,
// "type": "text",
// "senderId": "3bb179af-bcc5-4fe0-9dac-c05688484649",
// "payload": {
// "text": "Hello, GoEasyIM"
// },
// "receiverId": "fdee46b0-4b01-4590-bdba-6586d7617f95"
// }
};
//监听和接收单聊消息
im.on(GoEasyIM.EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);