Vue 集成环信 SDK
·
一、准备工作
- 注册与创建应用
- 前往环信官网进行注册登录。
https://doc.easemob.com/document/web/quickstart.html - 创建一个新的应用,获取对应的AppKey等必要信息,这些将在后续配置中使用。
- 前往环信官网进行注册登录。
- 安装 SDK
使用 npm 包管理器安装环信 Web SDKnpm install easemob-websdk --save
二、引入和初始化 SDK
- 在主入口文件或使用的地方引入 SDK
- 通常在项目的主入口文件(如
main.js)中引入环信SDK:import WebIM from 'easemob-websdk' - 可以将 WebIM 对象挂载到 Vue 实例上,以便在全局范围内使用,例如
Vue.prototype.$WebIM = WebIM。
- 通常在项目的主入口文件(如
- 配置并初始化环信实例
- 在项目初始化阶段,一般是在
main.js或某个专门的初始化文件中对环信实例进行配置和初始化。示例代码如下:
创建一个参数配置文件 WebIMConfig.js,如下:
创建一个 WebIM.js 文件,进行环信 SDK 的初始化配置,如下:/** * 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 = { /* * Application AppKey */ appkey: '替换自己的 appkey', /* * Application Host */ Host: '替换自己的 Host', /* * 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, /** * Whether to use window.doQuery() * @parameter {Boolean} true or false */ isWindowSDK: false, /** a * @parameter {Boolean} true or false */ isSandBox: false, // 内部测试环境,集成时设为false /** * Whether to console.log in strophe.log() * @parameter {Boolean} true or false */ isDebug: true, /** * Whether to show logs in strophe * @parameter {Boolean} true or false */ isStropheLog: false, /** * will auto connect the xmpp server autoReconnectNumMax times in background when client is offline. * won't auto connect if autoReconnectNumMax=0. */ autoReconnectNumMax: 5, /** * the interval secons between each atuo reconnectting. * works only if autoReconnectMaxNum >= 2. */ autoReconnectInterval: 2, /** * webrtc supports WebKit and https only */ isWebRTC: true, // window.RTCPeerConnection && /^https\:$/.test(window.location.protocol), /** * cn: chinese * us: english */ i18n: 'us', /* * 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: true, /** * Size of message cache for group chating like group, chatroom etc */ groupMessageCacheSize: 200, /** * 5 actual logging methods, ordered and available: * 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR' */ loglevel: 'ERROR', /** * enable localstorage for history messages */ enableLocalStorage: true, // AgoraAppId: '15cb0d28b87b425ea613fc46f7c9f974' /* 需要替换成自己的声网 appId,此 appId 有限量,仅供参考使用,同时获取声网 token 的接口仅能供此 appId 使用,换成自己的 appId 后需要自己去实现 app server 获取声网token。 */ }; export default config;
import config from './WebIMConfig'; // 环信 websdk import websdk from 'easemob-websdk'; // 初始化IM SDK let WebIM = {}; WebIM = window.WebIM = websdk; WebIM.config = config; // 初始化客户端。相关的参数配置,详见 API 参考中的 `Connection` 类。 WebIM.conn = new WebIM.connection({ isReport: false, appKey: WebIM.config.appkey,//替换为你自己在管理后台注册的App Key isMultiLoginSessions: WebIM.config.isMultiLoginSessions, https: WebIM.config.https,//是否指定为 HTTPS,浏览器环境默认根据使用域名自行判断 isAutoLogin: true,// 是否自动登录 heartBeatWait: WebIM.config.heartBeatWait,//心跳间隔(单位为毫秒),默认 30000ms autoReconnectNumMax: WebIM.config.autoReconnectNumMax,//最大重连次数 autoReconnectInterval: WebIM.config.autoReconnectInterval,//每次自动重连之间的间隔秒数。仅当autoReconnectMaxNum >= 2时有效 isStropheLog: WebIM.config.isStropheLog,//是否在Strophe中显示日志 delivery: WebIM.config.delivery,//是否开启已送达回执。-true:开启;-(默认)false:关闭 // 公有云 isHttpDNS 默认配置为true,是否开启 DNS,防止 DNS 劫持,-(默认)true:开启 DNS,- false:不开启 DNS。 isHttpDNS: WebIM.config.isHttpDNS }); export default WebIM;最后将 WebIM.js 文件引入项目的入口文件 main.js 中,就可以再项目中使用 WebIM 实例。
- 在项目初始化阶段,一般是在
三、处理消息和事件监听
- 设置事件监听器
- 为了使环信 SDK 能够正常工作,需要处理各种事件,如消息接收、连接状态变化等。在初始化环信实例后,可以设置注册事件监听器,例如:
WebIM.conn.addEventHandler('connection&message', { onConnected: () => { console.log('环信链接成功的回调') }, onDisconnected: () => { console.log('断开链接的回调') }, onTextMessage: (message) => { console.log('收到文本消息的回调') }, onError: (error) => { console.log('错误的回调', error) } })connection&message 表示同时监听连接状态和接收消息,也可以分开监听,如下:
// 监听连接状态 WebIM.conn.addEventHandler('connection', { onConnected: (data) => { console.log('连接成功的回调') // 此时可以进行加入聊天室操作 }, onDisconnected: (data) => { console.log('断开链接的回调') }, }) //监听接收消息 WebIM.conn.addEventHandler('message', { onTextMessage: (message) => { console.log('收到文本消息的回调' ,message) }, onError: (error) => { console.log('发生错误回调',error) }, onCustomMessage: message => { console.log('收到自定义消息的回调' ,message); }, })addEventHandler 用于注册监听函数,它的第一个参数是自己定义的字符串,定义的时候,通常语义化,如监听连接状态,通常定义为 connection ,第二个参数是监听的事件类型
- 为了使环信 SDK 能够正常工作,需要处理各种事件,如消息接收、连接状态变化等。在初始化环信实例后,可以设置注册事件监听器,例如:
- 根据业务需求扩展其他事件的监听
根据实际需求,还可以监听更多类型的事件,如表情消息、图片消息、自定义消息等,以满足不同的聊天场景需求。
四、实现用户相关操作
- 注册用户(可选)
如果允许用户自主注册账号,则需要调用环信提供的注册接口来实现用户注册功能。一般是通过向环信服务器发送请求来完成注册流程。
虽然客户端可以用registerUser注册用户,但在实际项目中,尤其是生产环境,更推荐使用REST API或服务端代理的方式进行用户注册,以确保系统的安全性和可维护性。 - 用户登录
调用环信的登录方法,传入用户名、密码等信息进行登录认证。登录成功后才能加入聊天室与其他用户进行交流。例如:WebIM.conn.open({ user: 'username', // 用户名 pwd: 'password', // 密码 appKey: WebIM.config.appkey, }) .then(() => { console.log("login success"); }) .catch((reason) => { console.log("login fail", reason); }); - 加入聊天室
- 使用环信提供的 API 让用户加入指定的聊天室。可以通过群组 ID 或其他标识来确定要加入的聊天室。例如:
WebIM.conn.joinChatRoom({ roomId: roomId, // 聊天室id leaveOtherRooms:true,// 加入聊天室时,是否退出已加入的聊天室 true--退出 success: (data) => { console.log('加入聊天室成功') }, error:(err) =>{ console.log('加入聊天室失败--err', err.type) } });用户成功加入聊天室后,其他成员会在
onChatroomEvent回调里收到operation:'memberPresence' -
设置事件监听,监听聊天室事件
// 收到聊天室事件的回调 WebIM.conn.addEventHandler("CHATROOM", { onChatroomEvent: (e) => { switch (e.operation) { // 用户加入聊天室事件 case "memberPresence": // 当有人加入聊天室时触发 break; case 'destroy': // 当聊天室销毁时触发 break; case 'memberAbsence': // 当有人离开聊天室时触发 break; } } });
- 使用环信提供的 API 让用户加入指定的聊天室。可以通过群组 ID 或其他标识来确定要加入的聊天室。例如:
- 退出聊天室
若某成员退出聊天室,其他成员会在 onChatroomEvent 回调里收到 "operation: 'memberAbsence'WebIM.conn.leaveChatRoom({ roomId:roomId }).then(res => { console.log(res) }).catch(err => { console.log(err) }) - 获取对话历史消息
const historyOption = { // 聊天室ID targetId:roomId, // 每次获取的消息条数。默认值为 20,最大值是50 pageSize:50, // 起始消息 ID,默认值为 -1,即从最新消息开始 cursor:-1, // 会话类型:(默认) `singleChat`:单聊;`groupChat`:群聊;`chatRoom`:聊天室聊天 chatType: "chatRoom", // 是否选择正向拉取历史消息(从最老向最新拉取):(默认)`up`:向上搜索;`down`:向下搜索 searchDirection: "down", // 查询结束时间戳,单位为毫秒 endTime:endTime } WebIM.conn.getHistoryMessages(historyOption).then((res) => { // 成功获取历史消息。 let { isLast, messages,cursor } = res; // 返回的数据是否为最后一页数据 true:是 false:否 if (!isLast) { // 当返回的数据条数小于请求中设置的消息条数时,返回 true,否则为 false historyOption.cursor = cursor; // 获取下一页的历史信息 } }) .catch((e) => { // 获取失败。 });
更多推荐


所有评论(0)