W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
解釋:監(jiān)聽(tīng) WebSocket 接受到服務(wù)器的消息事件。
Function callback
屬性名 | 類型 | 必填 | 默認(rèn)值 | 說(shuō)明 |
---|---|---|---|---|
data | String/ArrayBuffer | 是 | 服務(wù)器返回的消息 |
<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);
}
});
});
}
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: