How to construct a reliable communication channel between the web and fast application?

Author: empty leaf 
Source: bbs.quickapp.cn/forum.php?m...

background

Fast application version: 1020

When using web components communicate between applications and web pages faster, and there are several found:

1, will be prompted to web component does not support message event, but is actually supported (only a small problem on the tips) when running 'npm run watch'

2, information is sent to the web application fast, fast web page send information to the application, the name of the method are used in the postMessage, but the data format is not consistent, convenient to use

3, the message will be lost (for example web client to a message handler has not performed where the page message to give the like)

4, when the fast web application to send information, fast application information will be sent to the back page

Feature

So here it took some effort to do the auxiliary library, features:

1, the transmission order message

2, the message will not be lost, guaranteed to arrive

3, the message is not repeatedly received (de-emphasis)

4, the message type classification, monitoring mechanisms similar incidents, more convenient

Fast application side code

Fast application, the channel.js create a new document, which reads:

<template>
    <web id="web" src="xxx" @message="{{onMessage}}"></web>
</template>

<script>
    import Channel from './channel'

    export default {
        channel: null,
        onInit() {
            this.channel = new Channel(this, 'web')

            //通道监听
            this.channel.on('type1', function (data) {
                //处理收到的数据
            })

            //发送信息
            this.channel.sendMsg('type2', {
                //数据
            })
        },
        onMessage(param) {
            this.channel.onMsg(param)
        },
    }
</script>复制代码

Web-side code

Web client js (can be copied to create a new script or js script):

/**
 * (在html端,实际上一个页面只能new一个通道)
 *
 * 通道,用来与html进行可靠的通信
 *
 * 1. 有序
 * 2. 回传与ack机制,保证到达
 * 3. id验证机制,去重
 *
 * @param logger {Function} 日志记录器,可为null
 * @param timeout {Number} 超时时间,超时后会重试,单位ms,默认1000
 */
var Channel = function (logger, timeout) {
    timeout = timeout || 1000

    if (!logger) logger = () => {}

    var that = this

    //消息id生成器
    that.idGenerator = 0
    //消息发送队列
    that.sendQueue = [
        // {
        //     data: {},
        //     resolve: Object,
        // },
    ]
    //***列表
    that.listeners = {
        // type: [listener1, listener2],
    }

    //当前接收的消息id
    that.receivedId = 0

    /**
     * @param type {String} 消息类型
     * @param data {Object} 消息内容
     * @return {Promise}
     */
    that.sendMsg = function (type, data) {
        var resolve;
        var promise = new Promise(resolve_ => resolve = resolve_)
        that.sendQueue.push({
            data: {
                pType: 'msg',
                id: ++that.idGenerator,
                type: type,
                data: data,
            },
            resolve
        })
        return promise
    }

    /**
     * 监听
     * @param type 消息类型
     * @param callback 回调
     */
    that.on = function (type, callback) {
        var typeListeners = that.listeners[type] || []
        that.listeners[type] = typeListeners
        typeListeners.push(callback)
    }

    /**
     * 收到消息时调用(设置为onmessage的处理函数)
     */
    that.onMsg = function (message) {
        logger('[收到消息]' + message)
        var {pType, id, type, data} = JSON.parse(message)

        if (pType === 'ack') {//ack
            if (id === that.idGenerator) {//是当前的ack,有效,删除元素
                var nowPackets = that.sendQueue.splice(0, 1);
                that.valid_(nowPackets.length === 1)
                nowPackets[0].resolve()
            }
        } else if (pType === 'msg') {//正常消息
            if (id === that.receivedId + 1) {//是下个准备接收的包,有效
                //更新缓存值
                that.receivedId++
                //处理
                var typeListeners = that.listeners[type] || []
                logger('[处理消息]类型: ' + type + ' 处理器数量: ' + typeListeners.length)
                for (var i = 0; i < typeListeners.length; i++) {
                    try {
                        typeListeners[i](data)
                    } catch (e) {
                        logger('[处理异常]'+JSON.stringify(e))
                    }
                }
                //响应ack
                that.send_({
                    pType: 'ack',
                    id,
                })
            }
        } else {//没有pType,忽略
            return
        }
    }

    /**
     * 发包
     */
    that.send_ = function (packet) {
        var str = JSON.stringify(packet)
        system.postMessage(str)
        logger('[发送消息]' + str)
    }

    /**
     * 下个包
     */
    that.next_ = function () {
        if (that.sendQueue.length > 0) {
            that.send_(that.sendQueue[0].data)
        }
    }

    /**
     * 验证
     */
    that.valid_ = function (bool, errMsg) {
        if (!bool) {
            throw new Error(errMsg || 'Valid Fail!')
        }
    }

    //计时器: 不断重试发送包
    setInterval(function () {
        that.next_()
    }, timeout)

    //计时器: ping
    //(必须不断地ping,因此html不发请求到app,那么app发送给html的消息就不会过来,蛋疼)
    setInterval(function () {
        that.send_({})
    }, 200)

    //对接
    system.onmessage = that.onMsg
}
复制代码


Use web client (Reference):

var channel = new Channel()

//通道监听
channel.on('type1', function (data) {
    //处理收到的数据
})

//发送信息
channel.sendMsg('type2', {
    //数据
})
复制代码

At last

1, fast application send information to a web page, official documents written message format is messageString, but this format in the document did not say what, in the official demo where you can see the commented code in the format {message: 'xxx '}

2, pages side logging poor display


Related Reading:

A front-end application development faster siege lion road

Usage fast application and FAQs

Talk fast application development - deployment and debugging

Fast application development Getting Started Guide


Written in the last

In last year's Developer Challenge essay, we collect through multiple joint community activities a lot of high-quality articles that guide into the pit, multiple aspects of open source projects, development of templates, frequently asked questions and summarizing, these elements provide a reference for many developers thank you for your support and participation in this year of our writing activities continues, interested developers can view details read the original point oh!

In last year's Developer Challenge essay, we collect through multiple joint community activities a lot of high-quality articles that guide into the pit, multiple aspects of open source projects, development of templates, frequently asked questions and summarizing, these elements provide a reference for many developers thank you for your support and participation in this year of our writing activities continues, interested developers can go to the following view details bbs.quickapp.cn/forum.php?m...


Eco-fast application platform - enabling developers to develop future scenarios


Reproduced in: https: //juejin.im/post/5d0743a451882569821e5f56

Guess you like

Origin blog.csdn.net/weixin_34347651/article/details/93177877