目录

websocket

接口声明

在manifest.json文件的 features属性中增加如下配置。

{"name": "system.websocketfactory"}

导入模块

在调用接口页面的<script>部分增加如下配置。

import websocketfactory from '@system.websocketfactory'

或

var websocketfactory = require("@system.websocketfactory")

使用限制

限制条件

说明

使用终端

手机、平板、智慧屏、车机

适用区域

全球

接口定义

接口

描述

websocketfactory.create(OBJECT)

创建一个WebSocket连接,每次成功调用websocketfactory.create将返回一个新的websocket对象。

websocket.send(OBJECT)

使用create创建的对象websocket发送消息。

websocket.close(OBJECT)

关闭websocket连接。

websocket.onopen(OBJECT)

监听websocket连接打开的状态。

websocket.onmessage(OBJECT)

消息事件的监听,用于接收服务端发来的message。

websocket.onclose(OBJECT)

关闭连接的监听。

websocket.onerror(OBJECT)

错误事件的监听器。

[h2]websocketfactory.create(OBJECT)

描述

创建一个WebSocket连接,每次成功调用websocketfactory.create将返回一个新的websocket对象。

从1060版本开始,可以通过 manifest.json 的 config.network 进行网络超时的配置。

创建Websocket的个数不受限制。

OBJECT参数

参数

类型

是否必填

说明

url

string

是

开发者服务器接口地址,必须是wss或ws协议。

header

object

否

HTTP Header,header中不能设置Referer。

protocols

array

否

子协议组。

示例代码

var websocket = websocketfactory.create({
    url: 'ws://echo.websocket.org',
    header:{
        'content-type': 'application/json'
    },
    protocols: ['protocol1']
})

[h2]websocket.send(OBJECT)

描述

使用create创建的对象websocket发送消息。

OBJECT参数

参数

类型

默认值

是否必填

说明

data

string | arraybuffer

-

是

需要发送到服务器的数据,数据大小不能超过16M。

success

function

-

否

接口调用成功的回调函数。

fail

function

-

否

接口调用失败的回调函数

示例代码

websocket.send({
    data:'send message',
    success:function() {
        console.log('success');
    },
    fail:function() {
        console.log('failed');
    }
}) 
sendMessage: function () {
    var that = this;
    var buffer = new ArrayBuffer(4);
    var a = new Uint8Array(buffer);
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;
    if (that.websocket) {
        that.websocket.send({
            data: buffer,
            success: function () {
                console.log('success');
                that.isSend = "发送成功";
            },
            fail: function () {
                console.log('failed');
                that.isSend = "发送失败";
            }
        })
    }
},

[h2]websocket.close(OBJECT)

描述

关闭websocket连接。

OBJECT参数

参数

类型

默认值

是否必填

说明

code

number

1000

否

关闭链接的状态号。

reason

string

-

否

关闭的原因。

success

function

-

否

接口调用成功的回调函数。

fail

function

-

否

接口调用失败的回调函数。

示例代码

websocket.close({
    code: 1000,
    reason: 'close as normal',
    success: function() {
        console.log('close success');
    },
    fail: function() {
        console.log('close fail');
    }
})

[h2]websocket.onopen(OBJECT)

描述

监听websocket连接打开的状态。

OBJECT参数

参数

类型

是否必填

说明

callback

function

否

打开连接回调。

示例代码

websocket.onopen = function() {
    console.log('connect open');
}

[h2]websocket.onmessage(OBJECT)

描述

消息事件的监听,用于接收服务端发来的message。

OBJECT参数

参数

类型

是否必填

说明

callback

function

否

服务器返回消息事件回调。

callback返回参数:

参数

类型

说明

data

string | arraybuffer

监听器接收到的消息。

示例代码

websocket.onmessage = function (e) {
    console.log("onmessage e = "+e.data);
}
websocket.onmessage = function (e) {
    console.log("onmessage e = "+JSON.stringify(String.fromCharCode.apply(null, new Uint8Array(e.data))));
}

[h2]websocket.onclose(OBJECT)

描述

关闭连接的监听。

OBJECT参数

参数

类型

是否必填

说明

callback

function

否

关闭连接事件回调。

callback返回参数:

参数

类型

说明

code

number

服务器返回关闭的状态码。

reason

string

服务器返回的关闭原因。

wasClean

boolean

是否完全关闭。

code说明:

状态码

名称

1000

Normal Closure

1001

Going Away

1002

Protocol Error

1003

Unsupported Data

1005

No Status Recvd

1006

Abnormal Closure

1007

Invalid frame payload data

1008

Policy Violation

1009

Message too big

1010

Missing Extension

1011

Internal Error

1012

Service Restart

1013

Try Again Later

1014

Bad Gateway

1015

TLS HandShake

示例代码

websocket.onclose = function(e) {
    console.log("onclose e.code = "+e.code+", e.reason = "+e.reason+", wasClean = "+e.wasClean);
}

[h2]websocket.onerror(OBJECT)

描述

错误事件的监听器。

OBJECT参数

参数

类型

是否必填

说明

callback

function

否

错误信息的事件。

callback返回参数:

参数

类型

说明

data

string

监听器接收到的消息。

示例代码

websocket.onerror = function(e) {
    console.log("onerror e.data = "+e.data);
}

安全要求

对于HTTPS请求,对证书要求如下:

Demo

<template>
    <div>
        <div>
            <text>{{componentName}}</text>
        </div>
        <div>
            <text>连接指定url:{{isSuccess}}</text>
        </div>
        <input type="button" onclick="connectWebsocket" value="连接指定url" />
        <div>
            <text>连接指定url2:{{isSuccess2}}</text>
        </div>
        <input type="button" onclick="connectWebsocket2" value="连接指定url2" />
        <div>
            <text>连接指定url3:{{isSuccess3}}</text>
        </div>
        <input type="button" onclick="connectWebsocket3" value="连接指定url3" />
        <div>
            <text>发送信息:{{isSend}}</text>
        </div>
        <input type="button" onclick="sendMessage" value="发送消息" />
        <input type="button" onclick="closeWebsocket" value="关闭" />
        <div>
            <text>发送信息:{{isSend2}}</text>
        </div>
        <input type="button" onclick="sendMessage2" value="发送消息2" />
        <input type="button" onclick="closeWebsocket2" value="关闭2" />
        <div>
            <text>发送信息:{{isSend3}}</text>
        </div>
        <input type="button" onclick="sendMessage3" value="发送消息3" />
        <input type="button" onclick="closeWebsocket3" value="关闭3" />
    </div>
</template>
<style>
    @import '../Common/css/common.css';
    .item-container {
        margin-bottom: 50px;
        margin-right: 60px;
        margin-left: 60px;
        flex-direction: column;
    }
    .item-content {
        flex-direction: column;
        background-color: #ffffff;
        padding-left: 30px;
        padding-right: 30px;
        padding-top: 20px;
        padding-bottom: 20px;
        margin-bottom: 30px;
        align-items: flex-start;
    }
    .txt {
        padding-top: 15px;
        padding-bottom: 15px;
    }
</style>
<script>
    import websocketfactory from '@system.websocketfactory'
    export default {
        data: {
            componentName: 'Websocket',
            isSuccess: '',
            isSend: '',
            isSend2: '',
            isSend3: '',
            websocket: '',
            isSuccess2: '',
            isSuccess3: '',
            websocket2: '',
        },
        onInit: function () {
            this.$page.setTitleBar({ text: 'Websocket' })
        },
        connectWebsocket: function () {
            var that = this;
            that.websocket = websocketfactory.create({
                url: 'ws://echo.websocket.org'
            })
            that.websocket.onmessage = function (e) {
                console.log("onmessage e = " + e.data);
            }
            that.websocket.onclose = function (e) {
                console.log("onclose e.code = " + e.code + ", e.reason = " + e.reason + ", wasClean = " + e.wasClean);
            }
            that.websocket.onerror = function (e) {
                console.log("onerror e.data = " + e.data);
                that.isSuccess = "连接失败";
            }
            that.websocket.onopen = function () {
                console.log('connect open');
                that.isSuccess = "连接成功"
            }
        },
        sendMessage: function () {
            var that = this;
            if (that.websocket) {
                that.websocket.send({
                    data: 'send message',
                    success: function () {
                        console.log(' success');
                        that.isSend = "发送成功";
                    },
                    fail: function () {
                        console.log('failed');
                        that.isSend = "发送失败";
                    }
                })
            }
        },
        closeWebsocket: function () {
            var that = this;
            if (that.websocket) {
                that.websocket.close({
                    code: 1000,
                    reason: 'close as normal',
                    success: function () {
                        console.log('close success!!!');
                    },
                    fail: function () {
                        console.log('close fail');
                    }
                })
            }
        },
        connectWebsocket2: function () {
            var that = this;
            that.websocket2 = websocketfactory.create({
                url: 'ws://echo.websocket.org',
                header: {
                    'content-type': 'application/json'
                },
                protocols: ['protocol1']
            })
            that.websocket2.onmessage = function (e) {
                console.log("2 onmessage e = " + e.data);
            }
            that.websocket2.onclose = function (e) {
                console.log("2 onclose e.code = " + e.code + ", e.reason = " + e.reason);
            }
            that.websocket2.onerror = function (e) {
                console.log("2 onerror e.data = " + e.data);
                that.isSuccess2 = "连接失败";
            }
            that.websocket2.onopen = function () {
                console.log('2 connect open');
                that.isSuccess2 = "连接成功"
            }
        },
        sendMessage2: function () {
            var that = this;
            if (that.websocket2) {
                that.websocket2.send({
                    data: 'send2 message',
                    success: function () {
                        console.log('success2');
                        that.isSend2 = "发送成功";
                    },
                    fail: function () {
                        console.log('failed 2');
                        that.isSend2 = "发送失败";
                    }
                })
            }
        },
        closeWebsocket2: function () {
            var that = this;
            if (that.websocket2) {
                that.websocket2.close({
                    code: 1000,
                    reason: 'close as normal',
                    success: function () {
                        console.log('close2 success!!!');
                    },
                    fail: function () {
                        console.log('close2 fail');
                    }
                })
            }
        },
        connectWebsocket3: function () {
            var that = this;
            that.websocket3 = websocketfactory.create({
                url: 'ws://echo.websocket.org',
                header: {
                    'content-type': 'application/json'
                },
                protocols: ['protocol1']
            })
            that.websocket3.onmessage = function (e) {
                console.log("3 onmessage e = " + JSON.stringify(String.fromCharCode.apply(null, new Uint8Array(e.data))));
            }
            that.websocket3.onclose = function (e) {
                console.log("3 onclose e.code = " + e.code + ", e.reason = " + e.reason);
            }
            that.websocket3.onerror = function (e) {
                console.log("3 onerror e.data = " + e.data);
                that.isSuccess3 = "连接失败";
            }
            that.websocket3.onopen = function () {
                console.log('3 connect open');
                that.isSuccess3 = "连接成功"
            }
        },
        sendMessage3: function () {
            var that = this;
            var buffer = new ArrayBuffer(4);
            var a = new Uint8Array(buffer);
            a[0] = 1;
            a[1] = 2;
            a[2] = 3;
            a[3] = 4;
            if (that.websocket3) {
                that.websocket3.send({
                    data: buffer,
                    success: function () {
                        console.log('success3');
                        that.isSend3 = "发送成功";
                    },
                    fail: function () {
                        console.log('failed 3');
                        that.isSend3 = "发送失败";
                    }
                })
            }
        },
        closeWebsocket3: function () {
            var that = this;
            if (that.websocket3) {
                that.websocket3.close({
                    code: 1000,
                    reason: 'close as normal',
                    success: function () {
                        console.log('close3 success!!!');
                    },
                    fail: function () {
                        console.log('close3 fail');
                    }
                })
            }
        }
    }
</script>