Vue集成环信

Vue集成环信步骤详解(这里例子介绍一对一单聊)

效果图

在这里插入图片描述

1.注册登陆环信并创建用户

步骤:注册 => 登录 => 创建应用 => 创建应用用户
登录注册:环信登陆注册页面(https://console.easemob.com/user/login)

在这里插入图片描述
创建应用 (ps:应该有一个试用的,就是应用列表第一个,有的话可不用再创建)
在这里插入图片描述
【创建应用】页面:
appname:应用的ID,唯一
Appkey:环信自动生成的一串唯一标识,用来区别应用
产品名称:根据自己的需求填写
描述:根据自己的需求填写
注册模式:一般选择开放注册
在这里插入图片描述

创建应用用户 (至少创建两个,方便后面的一对一聊天通讯)
在这里插入图片描述

2.npm下载环信sdk

环信开发文档:开发文档链接(https://docs-im.easemob.com/im/web/intro/integration)

npm install easemob-websdk --save

3. 在自己的资源文件中新建(或自己去下载环信demo把里面的WebIMConfig.js拿过来)

WebIMConfig.js配置文件
initWeb.js 初始化文件
在这里插入图片描述

WebIMConfig.js配置文件代码

注意需要修改appKey(在应用详情中查看自己的appKey)

/**
 * git do not control webim.config.js
 * everyone should copy webim.config.js.demo to webim.config.js
 * and have their own configs.
 * In this way , others won't be influenced by this config while git pull.
 */

// for react native
// var location = {
//     protocol: "https"
// }



var config = {
    /*
     * websocket server
     * im-api-v2.easemob.com/ws 线上环境
     * im-api-v2-hsb.easemob.com/ws 沙箱环境
     */
    socketServer: (window.location.protocol === "https:" ? "https:" : "http:") + "//im-api-v2.easemob.com/ws",
    /*
     * Backend REST API URL
     * a1.easemob.com 线上环境
     * a1-hsb.easemob.com 沙箱环境
     */
    restServer: (window.location.protocol === "https:" ? "https:" : "http:") + "//a1.easemob.com",
    /*
     * Application AppKey
     */
    appkey: '自己应用的APPkey',
    /*
     * Application Host
     */
    Host: 'easemob.com',
    /*
     * Whether to use HTTPS
     * @parameter {Boolean} true or false
     */
    https: true,

    /*
    * 公有云配置默认为 true,
    * 私有云配置请设置 isHttpDNS = false , 详细文档:http://docs-im.easemob.com/im/web/other/privatedeploy
    */
    isHttpDNS: true,
    /*
     * isMultiLoginSessions
     * true: A visitor can sign in to multiple webpages and receive messages at all the webpages.
     * false: A visitor can sign in to only one webpage and receive messages at the webpage.
     */
    isMultiLoginSessions: true,
    /**
     * isSandBox=true:  socketURL: 'im-api.sandbox.easemob.com',  apiURL: '//a1.sdb.easemob.com',
     * isSandBox=false: socketURL: 'im-api.easemob.com',          apiURL: '//a1.easemob.com',
     * @parameter {Boolean} true or false
     */
    isSandBox: false, //内部测试环境,集成时设为false
    /**
     * Whether to console.log
     * @parameter {Boolean} true or false
     */
    isDebug: true,
    /**
     * will auto connect the websocket server autoReconnectNumMax times in background when client is offline.
     * won't auto connect if autoReconnectNumMax=0.
     */
    autoReconnectNumMax: 10,
    /**
     * webrtc supports WebKit and https only
     */
    isWebRTC: window.RTCPeerConnection && /^https\:$/.test(window.location.protocol),
    /*
     * Upload pictures or file to your own server and send message with url
     * @parameter {Boolean} true or false
     * true: Using the API provided by SDK to upload file to huanxin server
     * false: Using your method to upload file to your own server
     */
    useOwnUploadFun: false,
    /**
     *  cn: chinese
     *  us: english
     */
    i18n: 'cn',
    /*
     * Set to auto sign-in
     */
    isAutoLogin: true,
    /**
     * Size of message cache for person to person
     */
    p2pMessageCacheSize: 500,
    /**
     * When a message arrived, the receiver send an ack message to the
     * sender, in order to tell the sender the message has delivered.
     * See call back function onReceivedMessage
     */
    delivery: false,
    /**
     * Size of message cache for group chating like group, chatroom etc. For use in this demo
     */
    groupMessageCacheSize: 200,
    /**
     * 5 actual logging methods, ordered and available:
     * 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR'
     */
    loglevel: 'ERROR',

    /**
     * enable localstorage for history messages. For use in this demo
     */
    enableLocalStorage: true,

    deviceId: 'webim'
}
export default config

initWeb.js初始化文件代码
import websdk from 'easemob-websdk'
import config from './WebIMConfig.js'

//初始化
let conn = {};
WebIM.config = config;
conn = WebIM.conn = new WebIM.connection({
    appKey: WebIM.config.appkey,
    isHttpDNS: WebIM.config.isHttpDNS,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: WebIM.config.https,
    url: WebIM.config.socketServer,
    apiUrl: WebIM.config.restServer,
    isAutoLogin: WebIM.config.isAutoLogin,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    delivery: WebIM.config.delivery,
    useOwnUploadFun: WebIM.config.useOwnUploadFun
})
// WebIM.config 为之前集成里介绍的WebIMConfig.js


//回调
conn.listen({
    onOpened: function ( message ) {},         //连接成功回调 
    onClosed: function ( message ) {},         //连接关闭回调
    onTextMessage: function ( message ) {},    //收到文本消息
    onEmojiMessage: function ( message ) {},   //收到表情消息
    onPictureMessage: function ( message ) {}, //收到图片消息
    onCmdMessage: function ( message ) {},     //收到命令消息
    onAudioMessage: function ( message ) {},   //收到音频消息
    onLocationMessage: function ( message ) {},//收到位置消息
    onFileMessage: function ( message ) {},    //收到文件消息
    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);
    },
    onRecallMessage: function(message){},      //收到撤回消息回调
    onReceivedMessage: function(message){},    //收到消息送达服务器回执
    onDeliveredMessage: function(message){},   //收到消息送达客户端回执
    onReadMessage: function(message){},        //收到消息已读回执
    onCreateGroup: function(message){},        //创建群组成功回执(需调用createGroupNew)
    onMutedMessage: function(message){},       //如果用户在A群组被禁言,在A群发消息会走这个回调并且消息不会传递给群其它成员
    onChannelMessage: function(message){}      //收到整个会话已读的回执,在对方发送channel ack时会在这个回调里收到消息
});

export {conn};
新建两个可以互相聊天的页面

A页面

实现登陆,发送消息,接收消息(这里直接登陆了就没写登陆页面)

<template>
	<div>		
		<div id='msgBody' style="width: 80%;height: 500px;background-color: #fdffea;overflow: auto;">
			<div v-for='item in messageList'>
				<div v-if="item.from=='miss01'?true:false" >
					<div style="text-align: center;">{{item.time}}</div>
					<div style="float: right;">
						<p style="color: #00aaff;">{{item.from}}</p>
						<span >{{item.info}}</span>
					</div>
					<br style="clear: both;"/>	
				</div>
				<div v-else>
					<div style="text-align: center;">{{item.time}}</div>
					<div>
						<p style="color: #00aaff;">{{item.from}}</p>
						<span>{{item.info}}</span>
					</div>			
				</div>
			</div>
		</div>
		<div id='msgFooter'>
			<el-input type="textarea" :rows="3" v-model="inputMessage" @keyup.enter.native="sendMessage()" style="outline: none;"></el-input>
			<div>
				<el-button class="sendBnt" type="primary" @click="sendMessage()" round>发送(S)</el-button>
			</div>
		</div>
	</div>
</template>

import websdk from 'easemob-websdk'	
import {conn} from '../../../assets/utils/WebIM/initWeb.js'
//格式化时间
import {formatDate} from '../../../assets/utils/format.js';
export default{
	name:'IMChat',
	components:{
		
	},
	data(){		
		return{	
			user: 'miss01',  //自己应用下的用户id
			pwd: 'abc123',	//用户密码
			inputMessage:'',
			messageList:[], //消息
		}
	},
	created(){
		this.loginIM();
	},	
	methods:{
		//登陆
		loginIM(){
			var options = {
				user: this.user,
				pwd: this.pwd,
				appKey: WebIM.config.appkey,
				success: function (res) {
					console.log(res)
					console.log('成功')
				},
				error: function (err){
					console.log(err)
				}
			};
			conn.open(options);	
			this.getMessage();		
		},
		//发送消息
		sendMessage(){			
			if (!this.inputMessage || !(this.inputMessage.replace(/&nbsp;|\s/g, ''))) {
				this.$message.info('发送内容不能为空!');				
				return;
			}
			let that=this;
			let contentMsg=that.inputMessage;		
			let toID ='service00';   //收信息用户id
			let id = conn.getUniqueId();                 // 生成本地消息id
			let msg = new WebIM.message('txt', id);      // 创建文本消息
			msg.set({
				msg: contentMsg,                  // 消息内容
				to: toID,                          // 接收消息对象(用户id)
				chatType: 'singleChat',                  // 设置为单聊				                     
				success: function (id, serverMsgId) {					
					console.log('成功发送消息'); 					
					that.sendMessageSuccessful(contentMsg,toID,'txt');				
				}, 
				fail: function(e){							
					console.log("发送消息失败");  
				}
			});					
			conn.send(msg.body);
			that.inputMessage=null;
		},
		//成功发送消息,进行消息加入到聊天信息数组中
		sendMessageSuccessful(data,toID,type){
			console.log("存储信息中》》》》》");
			let userMsg={};
			userMsg.to=toID; 
			userMsg.from=this.user;
			userMsg.info=data;
			userMsg.time=formatDate(new Date(new Date().getTime()),'yyyy-MM-dd hh:mm');
			userMsg.msgType=type;
			//存储信息
			this.messageList.push(userMsg);		
		},
		// 集成收到文本信息方法
		getMessage(){
			let that=this;
			conn.listen({
				onOpened: function (message) {
					console.log('用户已上线') // 连接成功
				},
				onTextMessage: function ( message ) {
					console.log('收到文本信息')
					console.log(message)
					let date = formatDate(new Date(new Date().getTime()),'yyyy-MM-dd hh:mm');
					let value = {}
					// 普通文本信息
					value = {
						msgType: 'text',		      
						info: message.data,
						to: message.to,
						from: message.from,
						time: date
				    }
					that.messageList.push(value) // 添加到聊天信息数组中 
				}
			});			
		},		    	
	}
}

B页面

登陆发送消息接收消息代码与A页面相同,只是登陆的用户的Id和密码,以及收信息用户id需要修改,还有就是调整HTML聊天信息显示位置

需修改的地方
在这里插入图片描述
在这里插入图片描述

4.开两个浏览器页面实现一对一单聊

在这里插入图片描述
更多请关注后续博客

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值