在vue-cli里如何对接融云webIM

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_37938910/article/details/83060165

如何对接融云的webIM实时通讯云

读者您好,很开心能与一起分享我的项目收获,这里主要介绍一个本人在vue-cli里如何对接融云webIM实时通讯云,以及踩过的坑,项目为公司的一个3d线上展会项目,需要对接前端与后台的一对多的实时聊天功能,由于项目的工期紧张,于是采用了第三方实时通信云,一开始用的是环信,但是环信对web端不怎么友好,对安卓也是,然后重新选了融云即时通讯云,文末我会贴上完整代码。

首先打开融云官网,简单看一下融云的介绍

这里是融云的官网:https://www.rongcloud.cn
看了官方网站之后发现融云对于web端好像也不怎么友好,有安卓以及ios的demo,但是webIM的demo是基于react.js写的,奈何本人技术有限,还没有学react,看了看方法和api,于是打算自己基于vue写一个自己的样式放入到自己的项目里面去

引入融云的CDN

首先我们需要在vue的index.html里面引入融云的两个CDN

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- ========浏览器不启用更新机制======== -->
  <!-- <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
  <meta http-equiv="expires" content="0"> -->
  <!-- ======== end ========= -->
  <link rel="shortcut icon" href="staticBusys/20180915172116.png">
  <title>展派企业后台管理系统</title>
  <script src="https://cdn.ronghub.com/RongIMLib-2.3.3.min.js"></script>   //融云的CDN
  <script src="https://cdn.ronghub.com/RongEmoji-2.2.7.min.js"></script>   //融云提供的表情包CDN
</head>

<body>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>

</html>

初始化融云实时通讯云

初始化融云使用:RongIMLib.RongIMClient.init(appkey)这个方法
appkey由融云给的,token为自己账号从融云获取
初始化融云表情:RongIMLib.RongIMEmoji.init();

链接融云

	/**
     * 融云连接状态监听
     */
    RongIMClient.setConnectionStatusListener({
      onChanged: function(status) {
        switch (status) {
          case RongIMLib.ConnectionStatus.CONNECTED:
            //判断是否有GetQueryString().firmIm逻辑处理
            if (
              GetQueryString().firmIm &&
              GetQueryString().firmIm != undefined
            ) {
              that.targetId = GetQueryString().firmIm;
              that.sendHello(that);
            } else {
              that.targetId = list[that.activeIndex].targetId;
              that.getConversationList(that);
            }
            that.getUnreadCount();
            that.getTotalUnreadCount();
            break;
          case RongIMLib.ConnectionStatus.CONNECTING:
            console.log("正在链接");
            break;
          case RongIMLib.ConnectionStatus.DISCONNECTED:
            console.log("断开连接");
            break;
          case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
            console.log("其他设备登录");
            break;
          case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            console.log("域名不正确");
            break;
          case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
            console.log("网络不可用");
            break;
        }
      }
    });

    // 消息监听器
    RongIMClient.setOnReceiveMessageListener({
      // 接收到的消息
      onReceived: function(message) {
        // that.getConversationList(that)
        // 判断消息类型
        // if (that.$route.name == "消息提醒") {
        // if (message.senderUserId == GetQueryString().firmIm) {
        console.log(message.content.content);
        if (message.content.content != "") {
          that.scrollListDown();
          switch (message.messageType) {
            case RongIMClient.MessageType.TextMessage:
              that.$notify({
                message: message.senderUserId + "发来一条文字信息",
                type: "success"
              });
              var off = false;
              for (let n = 0; n < that.chatList.length; n++) {
                if (that.chatList[n].targetId == message.senderUserId) {
                  off = true;
                  message.sentTime = timeFormatNotime(message.sentTime);
                  message.content.content = RongIMLib.RongIMEmoji.emojiToHTML(
                    RongIMLib.RongIMEmoji.symbolToEmoji(message.content.content)
                  );
                  var record = that.chatList[n];
                  record.record.push(message);
                  that.$set(that.chatList, n, record);
                }
              }
              if (!off) {
                that.targetId = message.senderUserId;
                that.getHistroyMessage(that);
              }
              that.scrollTop();
              // that.text = "收到消息";
              that.text = "";
              // alert(1);
              // message.content.content => 消息内容
              break;
            case RongIMClient.MessageType.VoiceMessage:
              // 对声音进行预加载
              // message.content.content 格式为 AMR 格式的 base64 码
              break;
            case RongIMClient.MessageType.ImageMessage:
              that.$notify({
                message: message.senderUserId + "发来一条图片信息",
                type: "success"
              });
              for (let n = 0; n < that.chatList.length; n++) {
                if (that.chatList[n].targetId == message.senderUserId) {
                  message.sentTime = timeFormatNotime(message.sentTime);
                  var record = that.chatList[n];
                  record.record.push(message);
                  // that.chatList[n].record.push(message);
                  that.$set(that.chatList, n, record);
                }
              }
              // setTimeout(function(){
              that.scrollTop();
              // },1000)

              // message.content.content => 图片缩略图 base64。
              // message.content.imageUri => 原图 URL。
              break;
            case RongIMClient.MessageType.DiscussionNotificationMessage:
              // message.content.extension => 讨论组中的人员。
              break;
            case RongIMClient.MessageType.LocationMessage:
              // message.content.latiude => 纬度。
              // message.content.longitude => 经度。
              // message.content.content => 位置图片 base64。
              break;
            case RongIMClient.MessageType.RichContentMessage:
              // message.content.content => 文本消息内容。
              // message.content.imageUri => 图片 base64。
              // message.content.url => 原图 URL。
              break;
            case RongIMClient.MessageType.InformationNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.ContactNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.ProfileNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.CommandNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.CommandMessage:
              // do something...
              break;
            case RongIMClient.MessageType.UnknownMessage:
              // do something...
              break;
            default:
            // do something...
          }
        } else {
          that.getConversationList(that);
          that.scrollListTop();
        }
      }
      // } else {
      //   that.$notify({
      //     title: "提示",
      //     message: "你有新的消息,请前往聊天室查看",
      //     type: "success"
      //   });
      // }
      // }
    });
    /**
     *连接融云,连接融云必须写在init()方法之后,而在链接融云前,必须写监听事件
     */
    RongIMClient.connect(
      that.token,
      {
        onSuccess: function(userId) {
          that.userId = userId;
          that.ryName = localStorage["ryName"];
          that.$store.commit({
            type: "get_rcloud_userId",
            userid: userId
          });
        },
        onTokenIncorrect: function() {
          that.reset(that);
        },
        onError: function(errorCode) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";
              break;
            case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
              info = "不可接受的协议版本";
              break;
            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
              info = "appkey不正确";
              break;
            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
              info = "服务器不可用";
              break;
          }
          console.log(errorCode);
        }
      }
    );

链接融云前必须把状态监听器以及消息监听器写好

获取会话列表

链接融云之后我们要获取会话列表,融云服务器只会记录基本的会话信息,并不会保存用户的隐私信息,所以用户的头像昵称啥的得从自己的服务器上拉取,而获取会话列表需要在用户与用户之间建立关系之后才能存在于用户列表里。
获取会话列表如下:

    getConversationList(that) {
      var that = that;
      /*
	    文档:http://www.rongcloud.cn/docs/web_api_demo.html#会话接口
		  http://www.rongcloud.cn/docs/web.html#5_2、同步会话列表
		  http://www.rongcloud.cn/docs/api/js/Conversation.html
	    历史消息云存储开通位置:https://developer.rongcloud.cn/service/roam/rXxI4IAJjxRAD72SpQ==
    	注意事项:
	  	1:一定一定一定要先开通 历史消息云存储 功能,本服务收费,测试环境可免费开通
		  2:只有发过消息才能生成会话
	    */
      var conversationTypes = null; //具体格式设置需要补充
      var limit = 20; //获取会话的数量,不传或传null为全部,暂不支持分页
      var start = new Date().getTime();
      RongIMClient.getInstance().getConversationList(
        {
          onSuccess: function(list) {
            list.sort(function(a, b) {
              return a.sentTime > b.sentTime;
            });
            var title = "成功获取 " + list.length + " 个会话";
            for (let i = 0; i < list.length; i++) {
              list[i].number = 0;
              list[i].record = [];
              if (list[i].targetId == that.targetId) {
                list[i].check = true;
              } else {
                list[i].check = false;
              }
              for (let n = i + 1; n < list.length; n++) {
                if (list[i].targetId == list[n].targetId) {
                  list[i].number++;
                  list.splice(n, 1); //console.log(arr[j]);
                  n--;
                }
              }
              //获取自己服务器上的头像和昵称
              that.$ajax
                .post(
                  that.$Url + "/rongyun/getInfo",
                  that.$qs.stringify({
                    userId: list[i].targetId
                  })
                )
                .then(response => {
                  if (response.data.msg == "success") {
                    list[i].ryName = response.data.data.ryInfo.ryName;
                    list[i].ryIcon = response.data.data.ryInfo.ryIcon;
                  } else {
                    list[i].ryName = "获取失败";
                    list[i].ryIcon = "";
                  }
                })
                .catch(function(error) {
                  console.log(error);
                });
            }
            that.chatList = list;
            //获取历史消息
            that.getHistroyMessage();
          },
          onError: function(error) {
            // console.log("获取会话失败", error, start);
          }
        },
        conversationTypes,
        limit
      );
    },

到这一步的时候我们已经获取了会话列表,并从自己的服务器上拉取了用户名和头像

发送消息

在发送消息的时候我们需要指定一个targetId,即我这个消息应该发给谁

    sendTextMessage(textContent) {
      var that = this;
      var msg = new RongIMLib.TextMessage({
        content: textContent,
        extra: "附加信息"
      });
      var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
      var targetId = that.targetId; // 目标 Id
      RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
        onSuccess: function(message) {
          console.log(message);
          for (let i = 0; i < that.chatList.length; i++) {
            if (that.chatList[i].check) {
              message.sentTime = timeFormatNotime(message.sentTime);
              message.content.content = RongIMLib.RongIMEmoji.emojiToHTML(
                message.content.content
              );
              console.log(message);
              console.log(message.content.content);
              // that.chatList[i].record.push(message);
              var record = that.chatList[i];
              record.record.push(message);
              // that.chatList[n].record.push(message);
              that.$set(that.chatList, i, record);
              console.log(
                that.chatList[i].record[that.chatList[i].record.length - 1]
              );
            }
          }

          that.scrollTop();
          that.text = "";
          console.log(that.chatList);
          //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
          console.log("Send successfully");
        },
        onError: function(errorCode, message) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";
              break;
            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
              info = "未知错误";
              break;
            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
              info = "在黑名单中,无法向对方发送消息";
              break;
            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
              info = "不在讨论组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_GROUP:
              info = "不在群组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
              info = "不在聊天室中";
              break;
            default:
              info = x;
              break;
          }
          console.log("发送失败:" + info);
        }
      });
    },

在发送消息成功之后把数据渲染到DOM结构中就可以了。到这基本功能都有了,获取会话列表,接收消息,以及发送消息就基本完成了。其余的就是一些扩展,比如如何于用户主动建立联系,接收到消息以后如何处理,后面我会一步步写给大家。先给大家附上源码地址。(我忙里偷闲写的,时间有限)

下载源码地址

https://gitee.com/Q_Augly/vueAdmin.git

展开阅读全文

没有更多推荐了,返回首页