环信webIM即时通讯学习笔记
參考環信開發文檔
1、注冊環信即時通信云獲得appkey
(1)注冊賬號之后,登錄進入即時通信云管理后臺,并在我的應用下創建一個自己的應用,這樣就可得到應用的appkey了
2、引用本地文件
(1)下載web sdk并解壓后,將 /sdk/dist/strophe-1.2.8.min.js、/sdk/dist/websdk-1.4.11.js、/demo/javascript/dist/webim.config.js 拷貝到系統相應的目錄下。
(2)新建 html 文件并 嚴格按照如下順序 引入相關 js 腳本。
<script type='text/javascript' src='webim.config.js'></script>
<script type='text/javascript' src='strophe-1.2.8.min.js'></script>
<script type='text/javascript' src='websdk-1.4.11.js'></script>
(3)更改webim.config.js里的appkey,改為自己的appkey
3、使用環信
3.1連接
/*頭部連接*/
var conn = new WebIM.connection({
? ? isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
? ? https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
? ? url: WebIM.config.xmppURL,
? ? heartBeatWait: WebIM.config.heartBeatWait,
? ? autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
? ? autoReconnectInterval: WebIM.config.autoReconnectInterval,
? ? apiUrl: WebIM.config.apiURL,
? ? isAutoLogin: true
});
3.2注冊
//注冊用戶
var options = {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? username: userid,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? password: password,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? nickname: nickname,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? appKey: WebIM.config.appkey,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? success: function () {//注冊成功之后回調函數
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? error: function () {},
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? apiUrl: WebIM.config.apiURL
? ? ? ? ? ? ? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? ? ? ? ? ? ? conn.registerUser(options);
3.3登錄
/*登錄*/
var options = {
? ? apiUrl: WebIM.config.apiURL,
? ? user: user,
? ? pwd: password,
? ? appKey: WebIM.config.appkey
};
conn.open(options);
3.4監聽回調
conn.listen({
? ? onOpened: function ( message ) {}, ? ? ?//連接成功回調
? ? onClosed: function ( message ) {}, ? ? ? ? //連接關閉回調
? ? onTextMessage: function ( message ) {//收到文本消息
? ? ? ? console.log(message);
? ? ? ? console.log('收到'+message.from+'發送的消息:'+message.data);
? ? ? ? detailMessage(message.data,message.from,'text',message.id,'');
? ? ? ? showMessage();
? ? },
? ? onEmojiMessage: function ( message ) {//收到表情消息
? ? ? ? console.log('收到'+message.from+'發送的Emoji'+':'+message.data);
? ? ? ? //緩存數據
? ? ? ? for(var i=0;i<message.data.length;i++){
? ? ? ? ? ? var img = message.data[i];
? ? ? ? ? ? var string;
? ? ? ? ? ? if (img.type=='txt') {string = string+img.data;}
? ? ? ? ? ? else{string = string+'<img class="emoji" '+'src="'+img.data +'">';}
? ? ? ? }
? ? ? ? string = string.replace('undefined','');
? ? ? ? console.log(string);
? ? ? ? detailMessage(string,message.from,'text',message.id,'');
? ? ? ? showMessage();
? ? },
? ? onPictureMessage: function ( message ) {//收到圖片消息
? ? ? ? console.log(message);
? ? ? ? console.log('收到'+message.from+'發送的圖片'+':'+message.url);
? ? ? ? detailMessage(message.url,message.from,'picture',message.id,'');
? ? ? ? showMessage();
? ? },
? ? onCmdMessage: function ( message ) {}, ? ? //收到命令消息
? ? onAudioMessage: function ( message ) {}, ? //收到音頻消息
? ? onLocationMessage: function ( message ) {},//收到位置消息
? ? onFileMessage: function ( message ) {//收到文件消息
? ? ? ? console.log(message);
? ? ? ? console.log('收到'+message.from+'發送的文件'+':'+message.url);
? ? ? ? detailMessage(message.url,message.from,'file',message.id,message.filename);
? ? ? ? showMessage();
? ? },
? ? onVideoMessage: function (message) {
? ? ? ? var node = document.getElementById('privateVideo');
? ? ? ? var option = {
? ? ? ? ? ? url: message.url,
? ? ? ? ? ? headers: {
? ? ? ? ? ? ? ? 'Accept': 'audio/mp4'
? ? ? ? ? ? },
? ? ? ? ? ? onFileDownloadComplete: function (response) {
? ? ? ? ? ? ? ? var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
? ? ? ? ? ? ? ? node.src = objectURL;
? ? ? ? ? ? },
? ? ? ? ? ? onFileDownloadError: function () {
? ? ? ? ? ? ? ? console.log('File down load error.')
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? WebIM.utils.download.call(conn, option);
? ? }, ? //收到視頻消息
? ? onPresence: function ( message ) {}, ? ? ? //處理“廣播”或“發布-訂閱”消息,如聯系人訂閱請求、處理群組、聊天室被踢解散等消息
? ? onRoster: function ( message ) {}, ? ? ? ? //處理好友申請
? ? onInviteMessage: function ( message ) {}, ?//處理群組邀請
? ? onOnline: function () {}, ? ? ? ? ? ? ? ? ?//本機網絡連接成功
? ? onOffline: function () {}, ? ? ? ? ? ? ? ? //本機網絡掉線
? ? onError: function ( message ) {}, ? ? ? ? ?//失敗回調
? ? onBlacklistUpdate: function (list) { ? ? ? //黑名單變動
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 查詢黑名單,將好友拉黑,將好友從黑名單移除都會回調這個函數,list則是黑名單現有的所有好友信息
? ? ? ? console.log(list);
? ? },
? ? onReceivedMessage: function(message){}, ? ?//收到消息送達客戶端回執
? ? onDeliveredMessage: function(message){}, ? //收到消息送達服務器回執
? ? onReadMessage: function(message){}, ? ? ? ?//收到消息已讀回執
? ? onCreateGroup: function(message){}, ? ? ? ?//創建群組成功回執(需調用createGroupNew)
? ? onMutedMessage: function(message){} ? ? ? ?//如果用戶在A群組被禁言,在A群發消息會走這個回調并且消息不會傳遞給群其它成員
});
3.5發送文字消息(表情消息和文字消息一樣)
/* 發送文字消息,這里的所有消息都是發送到群組的,send_to是群組id,群組是在環信管理后臺建的,沒有在前端自己創建 */
function sendPrivateText() {
? ? var msg_content = $("#input_msg").val();//獲取文本內容
? ? if (msg_content.length==0) return;
? ? console.log('發送至'+send_to);
? ? var id = conn.getUniqueId(); ? ? ? ? ? ? ? ? // 生成本地消息id
? ? var msg = new WebIM.message('txt', id); ? ? ?// 創建文本消息
? ? msg.set({
? ? ? ? msg: msg_content, ? ? ? ? ? ? ? ? ?// 消息內容
? ? ? ? to: send_to, ? ? ? ? ? ? ? ? ? ? ? // 接收消息對象(用戶id)
? ? ? ? roomType: false,
? ? ? ? chatType: 'groupchat',
? ? ? ? success: function (id, serverMsgId) {
? ? ? ? ? ? console.log('send private text Success');
? ? ? ? ? ? $("#input_msg").val('');
? ? ? ? ? ? var emojiMessage = WebIM.utils.parseEmoji(msg_content);
? ? ? ? ? ? //緩存發送數據
? ? ? ? ? ? console.log('msg_content:'+emojiMessage);
? ? ? ? ? ? detailMessage(emojiMessage,"me",'text',msg.id,'');
? ? ? ? ? ? showMessage();
?
? ? ? ? },
? ? ? ? fail:function(){
? ? ? ? ? ? console.log("文字發送失敗!");
? ? ? ? }
? ? });
? ? msg.setGroup('groupchat');
? ? conn.send(msg.body);
}
3.6發送圖片消息
/* 發送圖片消息 */
function sendPrivateImg() {
? ? $("#image").change(function ?() {
? ? ? ? var id = conn.getUniqueId(); ? ? ? ? ? ? ? ? ? // 生成本地消息id
? ? ? ? var msg = new WebIM.message('img', id); ? ? ? ?// 創建圖片消息
? ? ? ? var input = document.getElementById('image'); ?// 選擇圖片的input ? id必填
? ? ? ? var file = WebIM.utils.getFileUrl(input); ? ? ?// 將圖片轉化為二進制文件
? ? ? ? var allowType = {'jpg': true,'gif': true,'png': true,'bmp': true};
? ? ? ? var img_url;
? ? ? ? if (file.filetype.toLowerCase() in allowType) {
? ? ? ? ? ? var option = {
? ? ? ? ? ? ? ? apiUrl: WebIM.config.apiURL,
? ? ? ? ? ? ? ? file: file,
? ? ? ? ? ? ? ? to: send_to, ? ? ? ? ? ? ? ? ? ? ? // 接收消息對象
? ? ? ? ? ? ? ? roomType: false,
? ? ? ? ? ? ? ? chatType: 'groupchat',
? ? ? ? ? ? ? ? onFileUploadError: function () { ? ? ?// 消息上傳失敗
? ? ? ? ? ? ? ? ? ? console.log('圖片發送失敗!');
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? onFileUploadComplete: function (aa) { ? // 消息上傳成功
? ? ? ? ? ? ? ? ? ? console.log('onFileUploadComplete');
? ? ? ? ? ? ? ? ? ? img_url = aa.uri+"/"+aa.entities[0].uuid;
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? success: function () { ? ? ? ? ? ? ? ?// 消息發送成功
? ? ? ? ? ? ? ? ? ? console.log('Success');
? ? ? ? ? ? ? ? ? ? //緩存發送數據
? ? ? ? ? ? ? ? ? ? console.log(img_url);
? ? ? ? ? ? ? ? ? ? detailMessage(img_url,"me",'picture',file.id,'');
? ? ? ? ? ? ? ? ? ? showMessage();
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? flashUpload: WebIM.flashUpload
? ? ? ? ? ? };
? ? ? ? ? ? msg.set(option);
? ? ? ? ? ? msg.setGroup('groupchat');
? ? ? ? ? ? conn.send(msg.body);
? ? ? ? }
? ? });
}
3.7發送文件消息
/* 發送文件消息 */
function sendPrivateFile() {
? ? ("#file").change(function ?() {
? ? ? ? var id = conn.getUniqueId(); ? ? ? ? ? ? ? ? ? // 生成本地消息id
? ? ? ? var msg = new WebIM.message('file', id); ? ? ? ?// 創建文件消息
? ? ? ? var input = document.getElementById('file'); ?// 選擇文件的input ?id必填
? ? ? ? var file = WebIM.utils.getFileUrl(input); ? ? ?// 將文件轉化為二進制文件
? ? ? ? var allowType = {'jpg': true,'gif': true,'png': true,'bmp': true,'zip': true,'txt': true,'doc': true,'pdf': true};
? ? ? ? var file_url;
? ? ? ? if (file.filetype.toLowerCase() in allowType) {
? ? ? ? ? ? var option = {
? ? ? ? ? ? ? ? apiUrl: WebIM.config.apiURL,
? ? ? ? ? ? ? ? file: file,
? ? ? ? ? ? ? ? to: send_to, ? ? ? ? ? ? ? ? ? ? ? // 接收消息對象
? ? ? ? ? ? ? ? roomType: false,
? ? ? ? ? ? ? ? chatType: 'groupchat',
? ? ? ? ? ? ? ? onFileUploadError: function () { ? ? ?// 消息上傳失敗
? ? ? ? ? ? ? ? ? ? console.log('文件發送失敗!');
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? onFileUploadComplete: function (aa) { ? // 消息上傳成功
? ? ? ? ? ? ? ? ? ? console.log('onFileUploadComplete');
? ? ? ? ? ? ? ? ? ? file_url = aa.uri+"/"+aa.entities[0].uuid;
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? success: function () { ? ? ? ? ? ? ? ?// 消息發送成功
? ? ? ? ? ? ? ? ? ? console.log('Success');
? ? ? ? ? ? ? ? ? ? //緩存發送數據
? ? ? ? ? ? ? ? ? ? detailMessage(file_url,"me",'file',file.id,file.filename);
? ? ? ? ? ? ? ? ? ? showMessage();
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? flashUpload: WebIM.flashUpload
? ? ? ? ? ? };
? ? ? ? ? ? msg.set(option);
? ? ? ? ? ? msg.setGroup('groupchat');
? ? ? ? ? ? conn.send(msg.body);
? ? ? ? }
? ? });
}
3.8緩存數據以及調用artTemplate模板顯示
/* 緩存消息處理 */
function detailMessage(data,from,type,id,filename){
? ? var localContent = new Array();
? ? if (localStorage[group]) {
? ? ? ? localContent = JSON.parse(localStorage[group]);
? ? }
? ? localContent[localContent.length] = {
? ? ? ? 'time':getNowFormatDate(),
? ? ? ? 'data':data,//數據
? ? ? ? 'from':from,//誰發的
? ? ? ? 'type':type,//文本類型 text,file,picture
? ? ? ? 'id':id,//消息id
? ? ? ? 'filename':filename//文件名字
? ? };
? ? localStorage[group] = JSON.stringify(localContent);//存儲本地;
}
?
/* 顯示發送和接收的消息消息 */
function showMessage(){
? ? //console.log('message:'+localContent);
? ? var localContent = JSON.parse(localStorage[group]);
? ? var obj = localContent[localContent.length-1];
? ? //獲取對應模板
? ? showBox(obj);//調用模板
? ? tobottom();
}
//模板
function showBox(obj){
? ? //綁定模板
? ? if (obj['from']=='me') {
? ? ? ? var html = '';
? ? ? ? if (obj.type=='text') {
? ? ? ? ? ? html = template("my_text",{time:obj.time,msg_content:obj.data});
? ? ? ? ? ? $(".chat_msg").append(imgShow(html));
? ? ? ? }else if (obj.type=='picture') {
? ? ? ? ? ? html = template("my_img",{time:obj.time,imgUrl:obj.data});
? ? ? ? ? ? $(".chat_msg").append(html);
? ? ? ? }else if (obj.type=='file') {
? ? ? ? ? ? html = template("my_file",{time:obj.time,filename:obj.filename,fileUrl:obj.data});
? ? ? ? ? ? $(".chat_msg").append(html);
? ? ? ? }
? ? }else{
? ? ? ? if (obj.type=='text') {
? ? ? ? ? ? html = template("other_text",{name:obj.from,time:obj.time,msg_content:obj.data});
? ? ? ? ? ? $(".chat_msg").append(imgShow(html));
? ? ? ? }else if (obj.type=='picture') {
? ? ? ? ? ? html = template("other_img",{name:obj.from,time:obj.time,imgUrl:obj.data});
? ? ? ? ? ? $(".chat_msg").append(html);
? ? ? ? }else if (obj.type=='file') {
? ? ? ? ? ? html = template("other_file",{name:obj.from,time:obj.time,filename:obj.filename,fileUrl:obj.data});
? ? ? ? ? ? $(".chat_msg").append(html);
? ? ? ? }
? ? }
}
3.9針對環信表情解釋
可以使用 WebIM.utils.parseEmoji()工具類來解釋,但是解釋得到的是一條含有img標簽的字符串,就是瀏覽器會將img標簽看做是字符串而不會將其解釋為img圖片標簽,因此需要將字符串轉換為DOM對象,使得瀏覽器能將其解釋為一張表情圖片,代碼如下:
/*匹配所有表情圖片的img標簽*/
function imgShow(obj){
? ? var emojiShow = obj.replace(new RegExp("<","gm"),"<");
? ? emojiShow = emojiShow.replace(new RegExp(">","gm"),">");
? ? emojiShow = emojiShow.replace(new RegExp(""","gm"),"'");
? ? return emojiShow;
}
另外還需要將表情圖片添加圖片資源里去,再添加圖片資源信息進去,如下:
WebIM.Emoji = {
? ? ? ? path: 'images/faces/',
? ? ? ? map: {
? ? ? ? ? ? '[):]': 'ee_1.png',
? ? ? ? ? ? '[:D]': 'ee_2.png',
? ? ? ? ? ? '[;)]': 'ee_3.png',
? ? ? ? ? ? '[:-o]': 'ee_4.png',
? ? ? ? ? ? '[:p]': 'ee_5.png',
? ? ? ? ? ? '[(H)]': 'ee_6.png',
? ? ? ? ? ? '[:@]': 'ee_7.png',
? ? ? ? ? ? '[:s]': 'ee_8.png',
? ? ? ? ? ? '[:$]': 'ee_9.png',
? ? ? ? ? ? '[:(]': 'ee_10.png',
? ? ? ? ? ? '[:\'(]': 'ee_11.png',
? ? ? ? ? ? '[:|]': 'ee_12.png',
? ? ? ? ? ? '[(a)]': 'ee_13.png',
? ? ? ? ? ? '[8o|]': 'ee_14.png',
? ? ? ? ? ? '[8-|]': 'ee_15.png',
? ? ? ? ? ? '[+o(]': 'ee_16.png',
? ? ? ? ? ? '[<o)]': 'ee_17.png',
? ? ? ? ? ? '[|-)]': 'ee_18.png',
? ? ? ? ? ? '[*-)]': 'ee_19.png',
? ? ? ? ? ? '[:-#]': 'ee_20.png',
? ? ? ? ? ? '[:-*]': 'ee_21.png',
? ? ? ? ? ? '[^o)]': 'ee_22.png',
? ? ? ? ? ? '[8-)]': 'ee_23.png',
? ? ? ? ? ? '[(|)]': 'ee_24.png',
? ? ? ? ? ? '[(u)]': 'ee_25.png',
? ? ? ? ? ? '[(S)]': 'ee_26.png',
? ? ? ? ? ? '[(*)]': 'ee_27.png',
? ? ? ? ? ? '[(#)]': 'ee_28.png',
? ? ? ? ? ? '[(R)]': 'ee_29.png',
? ? ? ? ? ? '[({)]': 'ee_30.png',
? ? ? ? ? ? '[(})]': 'ee_31.png',
? ? ? ? ? ? '[(k)]': 'ee_32.png',
? ? ? ? ? ? '[(F)]': 'ee_33.png',
? ? ? ? ? ? '[(W)]': 'ee_34.png',
? ? ? ? ? ? '[(D)]': 'ee_35.png'
? ? ? ? }
? ? };
另外若需要建選擇表情的面板,則自己寫樣式,將圖片放到面板上。
————————————————
版權聲明:本文為CSDN博主「lyxyldd」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/lyxyldd/article/details/77749845
總結
以上是生活随笔為你收集整理的环信webIM即时通讯学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用电梯服务器怎样解电梯显示E34,菱王n
- 下一篇: mac安装配置zsh