web前端vue融云即时通讯上手

1、采用v2.8版本
2、可以将https://cdn.ronghub.com/RongIMLib-2.8.latest.js,下载到项目里,以import形式导入,同时需要下载npm install --save @rongcloud/engine
import Vue from 'vue'
import App from './App.vue'
import router from './router'

import {rongyun} from '@/assets/rongyun/RongIMLib-2.8.latest.js' // 自己存放RongIMLib的位置

Vue.prototype.rongyun = rongyun

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
3、将初始化、设置监听、连接封装到一个rongyun.js文件中,作为初始化融云调用
// userInfo对象包含appKey,token
export default function init(userInfo,callbacks) {
    if (!userInfo.appKey || !userInfo.token){
        return false;
    }

    //公有云初始化
    RongIMLib.RongIMClient.init(userInfo.appKey);
    var instance = RongIMClient.getInstance();

    //连接状态监听器
    RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
            switch (status) {
                case RongIMLib.ConnectionStatus.CONNECTED:
                    console.log("链接成功 ");
                    callbacks.CONNECTED && callbacks.CONNECTED(instance);
                    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) {
            callbacks.Received && callbacks.Received(message);
        }
    });


    //开始链接
    RongIMClient.connect(userInfo.token, {
        onSuccess: function (id) {
            callbacks.Success && callbacks.Success(id);
        },
        onTokenIncorrect: function () {
            console.log('token无效');
        },
        onError: function (errorCode) {
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
        }
    });
}
4、在业务组件中调用rongyun.js中方法,完成融云初始化之后,可以获取会话列表|历史消息,设置RongIMClient.setOnReceiveMessageListener 监听接收消息,发送按钮事件写融云发送消息
<template>
  <div>
  </div>
</template>

<script>
import Exif from "exif-js";
import init from "../../assets/rongyun.js";
import { rongyun_appkey } from "@/lib/global"; // 存放rongyun_appkey的位置

export default {
  data() {
    return {
      token: '',
      targetId: '', // 消息接收方 类型String
      messageList: '', // 消息列表
      senderUserId: '', // 发送方 类型String
      headerImage: '',
      files: {
        type: '',
        name: ''
      }
    };
  },
  created() {
    this.getRongToken()
  },
  methods: {
    // 注册融云账号
    getRongToken() {
      // 向后端获取融云token(省略接口请求)
      this.token = '向后端获取到的token'
      this.initRongyun()
    },
    sendMsg() {
      let text;
      let msg;

      text = '这是发送的文本';
      msg = new RongIMLib.TextMessage({
        content: text, //消息内容
        extra: "附加信息",
        user: {
          // 可以这里放一些标记
        },
      })

      let conversationType = RongIMLib.ConversationType.PRIVATE; // 私聊
      let targetId = this.targetId; // 接收方的 userId
      let that = this;
      RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, {
        onSuccess: function (message) {
          let bb = that.messageList
          let newMsg = []
          if (bb) {
            bb.push(message)
            newMsg = bb
          } else {
            newMsg.push(message)
          }

          that.messageList = that.newMsg
          // 可以在自家服务器存一份聊天消息
        },
        onError: function (errorCode, message) {
          console.log(message, 'message');
        }
      }, false);
    },
    // 上传图片
    onRead(file) {
      // file.file.name;
      // file.file.type;
      let picValue = file.file;
      // const isJPG = file.file.type === "image/jpeg";
      // const isLt100 = file.file.size / 1024 / 100 < 1;
      // if (!isJPG) {
      //   Toast("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt100) {
      //   Toast("上传头像图片大小不能超过 100k!");
      // }
      // return isJPG && isLt100;

      this.imgPreview(picValue);
    },

    imgPreview(file) {
      let self = this;
      let Orientation;
      //去获取拍照时的信息,解决拍出来的照片旋转问题  Exif // 需要单独安装 https://www.npmjs.com/package/exif-js
      Exif.getData(file, function () {
        Orientation = Exif.getTag(this, "Orientation");
      });
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;

      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          //判断图片是否大于500K,是就直接上传,反之压缩图片
          if (this.result.length <= 500 * 1024) {
            self.headerImage = this.result;
            self.postImg();
          } else {
            img.onload = function () {
              let data = self.compress(img, Orientation);
              self.headerImage = data;
              self.postImg();
              Toast('大于500K')
            };
          }
        };
      }
    },
    // 压缩图片
    compress(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      //瓦片canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      // let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        // console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      //        铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = (width * height) / 1000000) > 1) {
        // console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
        //            计算每块瓦片的宽和高
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //修复ios上传图片的时候 被旋转的问题
      if (Orientation != "" && Orientation != 1) {
        switch (Orientation) {
          case 6: //需要顺时针(向左)90度旋转
            this.rotateImg(img, "left", canvas);
            break;
          case 8: //需要逆时针(向右)90度旋转
            this.rotateImg(img, "right", canvas);
            break;
          case 3: //需要180度旋转
            this.rotateImg(img, "right", canvas); //转两次
            this.rotateImg(img, "right", canvas);
            break;
        }
      }
      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },

    rotateImg(img, direction, canvas) {
      //最小与最大旋转方向,图片旋转4次后回到原方向
      const min_step = 0;
      const max_step = 3;
      if (img == null) return;
      //img的高度和宽度不能在img元素隐藏后获取,否则会出错
      let height = img.height;
      let width = img.width;
      let step = 2;
      if (step == null) {
        step = min_step;
      }
      if (direction == "right") {
        step++;
        //旋转到原位置,即超过最大值
        step > max_step && (step = min_step);
      } else {
        step--;
        step < min_step && (step = max_step);
      }
      //旋转角度以弧度值为参数
      let degree = (step * 90 * Math.PI) / 180;
      let ctx = canvas.getContext("2d");
      switch (step) {
        case 0:
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0);
          break;
        case 1:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, 0, -height);
          break;
        case 2:
          canvas.width = width;
          canvas.height = height;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, -height);
          break;
        case 3:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, 0);
          break;
      }
    },
    postImg() {
      //这里写后端上传接口,拿到服务器上图片的地址
      let file = this.dataURLtoFile(this.headerImage);
      let formData = new window.FormData();
      formData.append("file", file);

      // 上传到自己服务器
      // formData  headers: { "Content-Type": "multipart/form-data" }

      let imageUri = '后端返回的图片地址'; //融云要的格式
      let that = this;
      let base64Str = this.dataURLtoFile(this.headerImage);
      // console.log(base64Str, 'base64Str');

      let msg = new RongIMLib.ImageMessage({
        content: base64Str,
        imageUri: imageUri
      });
      let conversationType = RongIMLib.ConversationType.PRIVATE;
      let targetId = this.targetId;  // 目标 Id
      RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, {
        onSuccess: function (message) {
          that.messageList.push(message)
          // 可以自家服务器存一份聊天信息
        },
        onError: function (errorCode) {
          console.log('发送图片消息失败', errorCode);
        }
      });
    },
    //将base64转换为文件
    dataURLtoFile(dataurl) {
      let arr = dataurl.split(","),
        // 解码使用 base-64 编码的字符串
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], this.files.name, { type: this.files.type });
    },
    initRongyun() {
      let _this = this;
      const _token = this.token
      let userInfo = {
        appKey: `${rongyun_appkey}`,
        token: _token
      };

      // 消息监听器
      let callbacks = {
        CONNECTED: function (instance) {
          //传入实例参数
          //获取历史消息, !!!需要确认是否开通获取历史记录的服务
          let conversationType = RongIMLib.ConversationType.PRIVATE;
          let targetId = _this.targetId; //接收方的 userId
          let portraitUri = '' //头像 url
          instance.getHistoryMessages(
            conversationType,
            targetId,
            null,
            20,
            {
              onSuccess(list) {
                //渲染会话列表
                _this.messageList = list;
                return (_this.instance = instance);
              }
            },
            null
          );
        },
        Success: function (id) { },
        Received: function (message) { }
      };
      // 建立connect
      init(userInfo, callbacks);

      // 接收到的消息
      RongIMClient.setOnReceiveMessageListener({
        onReceived: function (message) {

          if (_this.messageList == '' || _this.messageList == null) {
            _this.messageList = []
            _this.messageList.push(message)

          } else {
            _this.messageList.push(message)
            callbacks.Received && callbacks.Received(message);
            _this.messageList.forEach(m => {
              m.senderUserId = _this.senderUserId
            })
            _this.messageList = _this.messageList
          }
        }
      })
    }
  }
};
</script>

targetId一定要String
即时通讯消息会存在未读状态,如果历史记录从自家公司服务器获取的话,会出现消息重复,需要过滤掉未读消息重叠部分

融云文档:https://docs.rongcloud.cn/v2/views/im/noui/guide/quick/include/web.html
https://support.rongcloud.cn/article/show/MzU=

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Heerey525

很开心我的内容帮助到你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值