SocketTask.onClose

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

# 方法参数

Function callback

# 示例

扫码体验
重新加载
请使用百度APP扫码

# 图片示例

# 代码示例

    <button type="primary" disabled="{{disabled}}" bindtap="socketTaskOnClose">socketTask.onClose</button>
    
    
    Page({
        data: {
            disabled: true
        },
        onShow() {
            const socketTask = swan.connectSocket({
                url: 'wss://echo.websocket.org',
                success: res => {
                    swan.showToast({
                        title: 'websocket 已打开',
                        icon: 'none'
                    });
                    this.setData('disabled', false)
                    console.log('connectSocket success', res.socketTaskId)
                },
                fail: err => {
                    swan.showToast({
                        title: 'websocket打开失败',
                        icon: 'none'
                    });
                    console.log('connectSocket fail', err);
                }
            });
            socketTask.onClose(res => {
                console.log('socketTask.onClose success', res);
                swan.showModal({
                    title: '监听到成功的关闭事件',
                    content: JSON.stringify(res.reason)
                });
            }),
            this.socketTask = socketTask;
        },
        socketTaskOnClose() {
            this.socketTask.close();
        }
    });