SocketTask.onClose

解释:监听 WebSocket 连接关闭事件。

# 方法参数

Function callback

# 示例

在开发者工具中预览效果

# 扫码体验

请使用百度APP扫码

# 图片示例

# 代码示例

  • 在 js 文件中

Page({
    data: {
        disabled: false
    },
    onTap() {
        let that = this;
        that.setData('disabled', true);
        const socketTask = swan.connectSocket({
            url: 'wss://echo.websocket.org',
            header: {},
            success: function (res) {
                console.log('connectSocket success', res.socketTaskId);
            },
            fail: function (err) {
                console.log('connectSocket fail', err);
            }
        });
        
        socketTask.onOpen(function (res) {
            that.socketTaskClose();
        })
        socketTask.onClose(function (res) {
            console.log('socketTask.onClose success', res);
            swan.showModal({
                title: '监听关闭事件成功',
                content: JSON.stringify(res.reason)
            });
        }),
        this.socketTask = socketTask;
    },
    socketTaskClose() {
        let that = this
        this.socketTask.close({
            success: res => {
                that.setData('disabled', false);
                console.log('关闭WebSocket成功', res);
                swan.showToast({
                    title: '关闭WebSocket成功',
                    icon: 'none'
                });
            },
            fail: err => {
                console.log('关闭WebSocket失败', err);
            }
        });
    }
});