リングレター3インスタントメッセージング-Web側SDKの簡単な統合
簡単なログイン/テキスト送信/友達リストの取得/テキストメッセージの受信を実現します(この記事はvuexを使用しない単純なものであり、メッセージレコードはローカルストレージに保存されます)1。SDK
をインストールします
npm install easemob-websdk
次に、utill構成ファイル。
特定の内部コード
。EMedia_x1v1_3.4.1.jsはデモで直接取得できるため、内部コードは
WebIMConfig.jsに貼り付けられません。
// for react native
// var location = {
// protocol: "https"
// }
var config = {
socketServer: '//im-api-v2.easemob.com/ws', // socket Server地址
restServer: '//a1.easemob.com', // rest Server地址
appkey: '自己账号的appkey', // App key
https: false, // 是否使用https
isHttpDNS: true, // 3.0 SDK支持,防止DNS劫持从服务端获取XMPPUrl、restUrl
isMultiLoginSessions: false, // 是否开启多页面同步收消息,注意,需要先联系商务开通此功能
isDebug: true, // 打开调试,会自动打印log,在控制台的console中查看log
autoReconnectNumMax: 2, // 断线重连最大次数
heartBeatWait: 30000, // 心跳间隔(只在小程序中使用)
delivery: false, // 是否发送已读回执
useOwnUploadFun: false // 是否使用自己的上传方式(如将图片文件等上传到自己的服务器,构建消息时只传url)
}
export default config
WebIM.js
import config from "./WebIMConfig";
import websdk from "easemob-websdk";
import webrtc from "./EMedia_x1v1_3.4.1";
import {
Message } from "element-ui";
function ack(message) {
var bodyId = message.id; // 需要发送已读回执的消息id
var msg = new WebIM.message("read", WebIM.conn.getUniqueId());
msg.set({
id: bodyId,
to: message.from
});
WebIM.conn.send(msg.body);
}
// 初始化IM SDK
var WebIM = {
};
WebIM = window.WebIM = websdk;
WebIM.config = config;
WebIM.conn = new WebIM.connection({
appKey: WebIM.config.appkey,
isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
https: WebIM.config.https,
isAutoLogin: true,
heartBeatWait: WebIM.config.heartBeatWait,
autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
autoReconnectInterval: WebIM.config.autoReconnectInterval,
isStropheLog: WebIM.config.isStropheLog,
delivery: WebIM.config.delivery,
//公有云 isHttpDNS 默认配置为true
isHttpDNS: WebIM.config.isHttpDNS,
});
export default WebIM;
第三に、ページの特定の使用
<template>
<div class="chat-container">
<div class="chat-menu">
<img src="../assets/logo.png" width="40px" height="40px" />
<i class="el-icon-chat-dot-square"></i>
<i class="el-icon-postcard"></i>
<i class="el-icon-help"></i>
</div>
<div class="chat-list">
<div class="select-veiw">
<el-input placeholder="请输入内容" v-model="selectFriends">
<i slot="prefix" class="el-input__icon el-icon-search"></i>
</el-input>
<el-button icon="el-icon-plus"></el-button>
</div>
<div class="select-list">
<div class="frends-item" v-for="item in frendsList" @click='sayTo(item.name)'
:style="{background:firendId===item.name?'#cccccc50':'none'}"
>
<img src="../assets/logo.png" width="40px" height="40px" />
<!-- <img :src="item.avatar" width="40px" height="40px"/> -->
<div class="item-content">
<p>{
{
item.name}}</p>
<p>{
{
item.lastMsg}}</p>
</div>
</div>
</div>
</div>
<div class="chat-veiw">
<div class="chat-veiw-top">{
{
firendId}}</div>
<div class="item-list-view">
<template v-for="(item,index) in wordsList">
<div class="transition fadeIn" :class="{'item-base':true,'item-right':username===item.nickName}">
<img :src="item.avatar" width="50px" height="50px" v-if="username!==item.nickName" />
<div class="item-content">
<span>{
{
item.nickName}}</span>
<div class="item-text">{
{
item.content}}</div>
</div>
<img :src="item.avatar" width="50px" height="50px" v-if="username===item.nickName" />
</div>
</template>
</div>
<div class="item-edit">
<div class="tools-veiw">
<i class="el-icon-full-screen"></i>
<i class="el-icon-picture-outline"></i>
<i class="el-icon-video-camera"></i>
</div>
<textarea rows="5" v-model="sendMsgContent" placeholder="请输入要发送的内容"></textarea>
<div class="send-veiw">
<button @click="sendMsg">发送</button>
</div>
</div>
</div>
</div>
</template>
<script>
import WebIM from "../utills/webim/WebIM";
export default {
props: {
},
data() {
return {
username: '我是谁',
sendMsgContent: '',
selectFriends: '',
firendId:null,
wordCell: {
nickName: '',
content: '',
type: 'text',
hxType: '',
avatar: require('../assets/logo.png')
},
wordsList: [],
token:'',
frendsList:[
{
nickName:'111',
avatar: require('../assets/logo.png'),
lastMsg:'1111'
},
{
nickName:'222',
avatar: require('../assets/logo.png'),
lastMsg:'1111'
},
]
}
},
created() {
//登录环信账号
this.initlogin()
var _this = this;
WebIM.conn.listen({
onOpened: function(message) {
// 连接成功回调
// 登录或注册成功后 跳转到好友页面
console.log('注册成功', JSON.stringify(message))
WebIM.conn.getRoster()//获取好友列表
},
//接受消息监听
onTextMessage: function(message) {
console.log('接收到文字的消息', message)
_this.GetMessage('text', message)
},
//加好友监听
onRoster: function (message) {
console.log("onRoster", message);
_this.frendsList=message
_this.frendsList.forEach(item=>{
localStorage.setItem(item.name+'List',JSON.stringify([]))
})
_this.firendId=message[0].name
_this.wordsList=JSON.parse(localStorage.getItem(message[0].name+'List'))
},
})
},
mounted() {
},
watch:{
firendId(val){
console.log(val+'111')
this.wordsList=JSON.parse(localStorage.getItem(val+'List'))
},
wordsList(val){
this.wordsList=val
}
},
methods: {
async initlogin() {
/*token登录*/
var _this=this
var options = {
apiUrl: WebIM.config.apiURL,
user: '登录用户',
pwd: '123456',
appKey: WebIM.config.appkey,
success: function (res) {
_this.token = res.access_token;
}
};
WebIM.conn.open(options);
var soptions = {
user: '登录用户',
accessToken: 'token',
appKey: WebIM.config.appkey
};
WebIM.conn.open(soptions);
},
sayTo(fid) {
this.firendId=fid
},
//发送消息
sendMsg() {
if (this.sendMsgContent) {
var _this = this
var id = WebIM.conn.getUniqueId(); //生成本地消息id
var msg = new WebIM.message('txt', id); //创建文本消息
msg.set({
msg: this.sendMsgContent, // 消息内容
to: _this.firendId, // 接收消息对象(用户id)
roomType: false,
chatType: 'chat', //个人聊天为chat 多人为groupchat
success: function() {
console.log('send private text Success');
let cell = {
nickName: '我是谁',
content: _this.sendMsgContent,
type: 'text',
avatar: require('../assets/logo.png')
}
_this.wordsList.push(cell);
localStorage.setItem(_this.firendId+'List',JSON.stringify(_this.wordsList))
_this.sendMsgContent = ''
},
fail: function(e) {
console.log("文字发送失败" + JSON.stringify(e));
}
});
//聊天室聊天/群聊
// if(chatType === "group" || chatType === "chatroom"){
// msg.setGroup("groupchat");
// }
WebIM.conn.send(msg.body);
}
},
//收消息
GetMessage(type, data) {
var _this = this
if (type === 'text') {
let cell = {
nickName: data.from,
content: data.sourceMsg,
type: 'text',
hxType: data.type,
avatar: require('../assets/logo.png')
}
_this.wordsList.push(cell)
}
localStorage.setItem(_this.firendId+'List',JSON.stringify(this.wordsList) )
}
},
filters: {
}
}
</script>
<style lang="scss" scoped="">
.chat-container {
display: flex;
align-items: center;
justify-content: center;
.chat-menu {
width: 80px;
height: 600px;
background: #42B983;
border: 1px solid #42B983;
display: flex;
flex-direction: column;
align-items: center;
i {
display: block;
width: 100%;
color: #fff;
font-size: 1.5rem;
background: rgba(120, 200, 140, 0.9);
padding: 10px 0;
margin: 10px 0;
}
img {
margin: 30px 0 50px;
border-radius: 5px;
border: 1px solid #fff;
background: rgba(120, 200, 140, 0.9);
}
}
.chat-list {
width: 300px;
height: 600px;
border: 1px solid blue;
border-right: none;
.select-veiw{
display: flex;
justify-content: space-around;
padding: 10px 0;
.el-input{
width: 160px;
}
.el-button{
width: 38px;
height: 38px;
padding: 0;
}
}
.select-list{
width: 100%;
height: 540px;
display: flex;
flex-direction: column;
justify-content: flex-start;
background: rgba(120, 200, 140, 0.2);
.frends-item{
// border-bottom: 1px solid #999;
// border-top: 1px solid #999;
margin-bottom:1px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
padding: 5px 10px;
img{
margin-right: 0.5rem;
background: #ccc;
border: 1px solid #fff;
border-radius: 5px;
}
.item-content{
p{
margin: 0;
padding: 0;
}
p:first-child{
line-height: 30px;
font-weight: 500;
}
p:last-child{
color: #999;
font-size: 13px;
}
}
}
}
}
.chat-veiw {
width: 800px;
height: 600px;
border: 1px solid blue;
.chat-veiw-top{
height: 60px;
line-height: 60px;
}
.item-list-view {
width: 100%;
height: 339px;
background: beige;
.item-base {
display: flex;
align-items: flex-start;
justify-content: flex-start;
padding: 0.5rem;
img {
background: royalblue;
border-radius: 50%;
margin-right: 1rem;
}
.item-content {
max-width: calc(60% - 1.2rem);
text-align: left;
span {
display: block;
margin-bottom: 0.5rem;
}
}
}
.item-right {
justify-content: flex-end;
img {
margin-right: 0;
}
.item-content {
margin-right: 1rem;
text-align: right;
.item-text {
background: #bdd986;
}
}
}
}
.item-edit {
width: 100%;
height: 200px;
background: #fff;
border-top: 1px solid #666;
.tools-veiw {
width: calc(100% - 1rem);
height: 40px;
text-align: right;
padding: 0 0.5rem;
i {
font-size: 1.3rem;
line-height: 40px;
margin: 0 0.5rem;
}
}
textarea {
box-sizing: border-box;
width: 100%;
height: 120px;
padding: 0.5rem;
border: none;
outline: none;
resize: none;
font-size: 1.2rem;
line-height: 2rem;
}
.send-veiw {
height: 40px;
text-align: right;
button {
height: 30px;
padding: 5px 20px;
margin: 0 1rem;
border: 1px solid #666;
outline: none;
background: #fff;
border-radius: 5px;
}
}
}
}
}
.item-text {
background: #fff;
border-radius: 0.2rem;
padding: 0.6rem;
}
</style>
SDKの簡単な統合が完了しました!今後も機能を追加していきます