SocketTask.onMessage

2020-08-21 10:56 更新

解釋:監(jiān)聽(tīng) WebSocket 接受到服務(wù)器的消息事件。

方法參數(shù)

Function callback

callback 返回參數(shù)說(shuō)明

屬性名類型必填默認(rèn)值說(shuō)明

data

String/ArrayBuffer

服務(wù)器返回的消息

示例 

在開(kāi)發(fā)者工具中打開(kāi)


圖片示例



代碼示例

<button type="primary" bindtap="socketTaskSend" disabled="{{disabled}}">socketTask.onMessage</button>
    Page({
        onShow() {
            const socketTask = new Promise((resolve, reject) => {
                const socketHandler = swan.connectSocket({
                    url: 'wss://echo.websocket.org',
                    header: {},
                    success: res => {
                        console.log('connectSocket success', res.socketTaskId);
                    },
                    fail: err => {
                        reject(err);
                        console.log('connectSocket fail', err);
                    }
                });
                socketHandler.onOpen(() => {
                    resolve(socketHandler);
                });
                socketHandler.onMessage((res) => {
                    swan.showModal({
                        title: '監(jiān)聽(tīng)到發(fā)送的數(shù)據(jù)為' + res.data,
                        content: res.dataType + '類型'
                    });
                });
            });
            this.socketTask = socketTask;
        },
    
        socketTaskSend() {
            this.socketTask.then(socketHandler => {
                socketHandler.send({
                    data: 'baidu',
                    success: res => {
                        swan.showToast({
                            title: '發(fā)送數(shù)據(jù)成功'
                        });
                        console.log('WebSocket發(fā)送數(shù)據(jù)成功', res);
                    },
                    fail: err => {
                        swan.showToast({
                            title: '發(fā)送數(shù)據(jù)失敗'
                        });
                        console.log('WebSocket發(fā)送數(shù)據(jù)失敗', err);
                    }
                });
            });
        }
    });


    以上內(nèi)容是否對(duì)您有幫助:
    在線筆記
    App下載
    App下載

    掃描二維碼

    下載編程獅App

    公眾號(hào)
    微信公眾號(hào)

    編程獅公眾號(hào)