W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
解釋:通過 WebSocket 連接發(fā)送數(shù)據(jù),需要先調(diào)用 swan.connectSocket,并在 swan.onSocketOpen 回調(diào)之后才能發(fā)送。
Object object
屬性名 | 類型 | 必填 | 默認(rèn)值 | 說明 |
---|---|---|---|---|
data | String | 是 | 需要發(fā)送的內(nèi)容 | |
success | Function | 否 | 接口調(diào)用成功的回調(diào)函數(shù) | |
fail | Function | 否 | 接口調(diào)用失敗的回調(diào)函數(shù) | |
complete | Function | 否 | 接口調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功、失敗都會(huì)執(zhí)行) |
<button type="primary" bindtap="sendSocketMessage">發(fā)送消息</button>
Page({
sendSocketMessage() {
swan.onSocketOpen(function () {
swan.sendSocketMessage({
data: 'baidu',
success: res => {
swan.showToast({
title: 'WebSocket發(fā)送數(shù)據(jù)成功',
icon: "none"
});
console.log('WebSocket發(fā)送數(shù)據(jù)成功', res);
},
fail: err => {
console.log('WebSocket發(fā)送數(shù)據(jù)失敗', err);
}
});
});
swan.connectSocket({
url: 'wss://echo.websocket.org',
header: {},
success: res => {
console.log('connectSocket success', res);
},
fail: err => {
console.log('connectSocket fail', err);
}
});
}
});
<button type="primary" bindtap="sendSocketMessage">發(fā)送消息</button>
Page({
sendSocketMessage() {
new Promise((resolve, reject) => {
const socketHandler = swan.connectSocket({
url: 'wss://echo.websocket.org',
header: {},
success: function (res) {
console.log('connectSocket success', res.socketTaskId)
},
fail: function (err) {
reject(err);
console.log('connectSocket fail', err);
}
});
socketHandler.onOpen(function () {
resolve(socketHandler);
});
})
.then(socketHandler => {
swan.sendSocketMessage({
data: 'baidu',
success: res => {
swan.showToast({
title: 'WebSocket發(fā)送數(shù)據(jù)成功',
icon: "none"
});
console.log('WebSocket發(fā)送數(shù)據(jù)成功', res);
},
fail: err => {
console.log('WebSocket發(fā)送數(shù)據(jù)失敗', err);
}
});
})
}
});
Android
錯(cuò)誤碼 | 說明 |
---|---|
302 | 找不到調(diào)起協(xié)議對(duì)應(yīng)端能力方法 |
202 | 解析失敗,請(qǐng)檢查參數(shù)是否正確 |
1001 | 執(zhí)行失敗 |
iOS
錯(cuò)誤碼 | 說明 |
---|---|
4 | 參數(shù)有誤 |
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)系方式:
更多建議: