
# 代码使用示例-用户接收消息
在用户接入时，发送连接请求携带着回调函数：开始轮询客服发来的消息，可参考UserForm.vue中的sendConnect方法。
```
sendConnect(){
    if (!this.$Chat.messageToken){
        this.$alert('接口校验信息错误！')
        return
    }
    let connectionData = {
        channel: 'WEB',
        controlType: "CONNECT",
        mediaType: "TEXT",
        content: "hello",
        sourceType: "CUSTOMER",
        to: this.$Chat.getChannelId(),
        "from": this.$Chat.userId,
        senderNickname: this.$Chat.userName
    }
    this.$Chat.send(connectionData,()=>{
        EventBus.$emit("startPoll");
    })
}
```
其中在send方法执行成功后，会执行EventBus.$emit("startPoll");的回调函数，意为向事件栈中发送startPoll事件，监听方法在MainContent.vue的mouted方法中：
```
//收消息
EventBus.$on("startPoll", this.pushAgentMessage);
```
会调用pushAgentMessage方法，具体方法如下：
```
//处理座席侧所有消息总函数
pushAgentMessage() {
    let that = this;
    let agentFunc = function (data) {
        if (data && data["downlinkMessages"]) {
            let downLinkMessage = data["downlinkMessages"];
            for (let i = 0; i < downLinkMessage.length; i++) {
                if (downLinkMessage[i]["sourceType"] === "AGENT") {
                    that.toAgent = true;
                    that.tipsObject.show = false;
                    that.tipsObject.showCancel = false;
                    if (that.isFirstToAgent) {
                        EventBus.$emit("changeTalkStatus", "toAgent")
                        that.isFirstToAgent = false;
                        EventBus.$emit("changeAgent", downLinkMessage[i]["senderNickname"])
                    }
                }
                if (downLinkMessage[i]["sourceType"] === "ROBOT") {
                    that.dealWithRobot(downLinkMessage[i]);
                    continue;
                }
                if (that.mediaType[downLinkMessage[i]["mediaType"]] != null) {
                    that.dealWithMedia(downLinkMessage[i]);
                    continue;
                }
                if (downLinkMessage[i]["controlType"] === "DISCONNECT") {
                    that.dealWithDrop();
                    continue;
                }
                //放入到展示区
                let content = that.$Utils.extractUrl(downLinkMessage[i]["content"])
                let msg = {
                    avatar: "zph",
                    text: that.$Utils.textChangeToImage(content),
                    type: 0,
                    time: that.$Utils.getDateString(),
                    float: "left",
                    userName: downLinkMessage[i]["senderNickname"]
                };
                that.pushInRecords(msg);
                if (downLinkMessage[i]["queueFlag"]) {
                    that.tipsObject.show = true;
                    that.queryQueue();
                }
            }
        }
        if (that.$Chat.isChatting) {
            EventBus.$emit("startPoll");
        }
    };
    setTimeout(() => {
        this.$Chat.poll(agentFunc);
    }, 100)
},
```
该方法是一个一直在轮询的方法，其中对于座席发来的不同消息类型，有不同的处理方式，关于座席返回的消息内容，可以参考接口参考中开放接口的poll方法；
其中一些方法的说明：
```
if (downLinkMessage[i]["sourceType"] === "AGENT") {
    that.toAgent = true;
    that.tipsObject.show = false;
    that.tipsObject.showCancel = false;
    if (that.isFirstToAgent) {
        EventBus.$emit("changeTalkStatus", "toAgent")
        that.isFirstToAgent = false;
        EventBus.$emit("changeAgent", downLinkMessage[i]["senderNickname"])
    }
}
```
当接收到第一条座席发来的信息时，会发送 changeTalkStatus 和 changeAgent 事件，其中changeTalkStatus事件会使监听方法去检查当前对话的座席是否支持点击通话（即音视频交谈），以及当前用户环境是否支持语音交谈，如果支持，会在demo的聊天工具栏中展示可以点击的音视频通话按键。
![](https://support.huaweicloud.com/devg-webdemo-cec/figure/zh-cn_image_0000001310256213.png)
changeAgent事件会使监听方法改变对话者的名称。
![](https://support.huaweicloud.com/devg-webdemo-cec/figure/zh-cn_image_0000001310136217.png)
```
if (downLinkMessage[i]["sourceType"] === "ROBOT") {
    that.dealWithRobot(downLinkMessage[i]);
    continue;
}
```
上述代码中会处理客服侧发来的消息，为机器人发来的消息类型。
```
if (that.mediaType[downLinkMessage[i]["mediaType"]] != null) {
    that.dealWithMedia(downLinkMessage[i]);
    continue;
}
```
上述代码中会处理客服侧发来的消息，为多媒体的消息类型。
```
//处理客服侧发送的媒体类型消息
dealWithMedia(data) {
    let fileId = data['content'];
    let mediaFileType = this.mediaType[data['mediaType']];
    let requestParam = {
        fileId: fileId,
        channel: 'WEB',
        fileType: mediaFileType,
        multiMedia: 'multiMedia'
    }
    let that = this;
    let itemType = this.itemType[data['mediaType']]
    let callbacks = function (respData) {
        if (respData['resultCode'] === '0') {
            let msg;
            if (itemType === 1) {
                let imgSrc = 'data:image/jpeg;base64,' + respData['fileStream'];
                let imgList = [];
                imgList.push(imgSrc);
                msg = {
                    avatar: "zph",
                    text: imgSrc,
                    type: itemType,
                    time: that.$Utils.getDateString(),
                    float: "left",
                    imgList: imgList
                };
            } else {
                let typeHeader = 'data:audio/mp3;base64,';
                let type = "audio/mp3";
                if (itemType === 2) {
                    typeHeader = 'data:video/mp4;base64,';
                    type = 'video/mp4';
                }
                let audioSource = typeHeader + respData['fileStream'];
                let arr = audioSource.split(',');
                let array = arr[0].match(/:(.*?);/);
                let mime = (array && array.length > 1 ? array[1] : type) || type;
                let bytes = window.atob(arr[1])
                let arrayBuffer = new ArrayBuffer(bytes.length);
                let uint8Array = new Uint8Array(arrayBuffer);
                for (let i = 0; i < bytes.length; i++) {
                    uint8Array[i] = bytes.charCodeAt(i);
                }
                let blobFile = new Blob([uint8Array], {
                    type: mime
                });
                let objectUrl = window.URL.createObjectURL(blobFile);
                msg = {
                    avatar: "zph",
                    text: objectUrl,
                    type: itemType,
                    time: that.$Utils.getDateString(),
                    float: "left",
                };
            }
 
            that.pushInRecords(msg);
        }
    }
    this.$Chat.downloadFileStream(callbacks, requestParam);
}
```
在识别到是多媒体消息时，会调用downloadFileStream的接口。
```
if (downLinkMessage[i]["controlType"] === "DISCONNECT") {
    that.dealWithDrop();
    continue;
}
```
上述代码中会处理客服侧发来的消息，为客户结束会话的消息类型。
