ap.connectSocket(OPTION | url, CALLBACK)
向指定服务器发起 WebSocket 连接请求。可直接传入一个字符串作为 OPTION.url 参数。
OPTION 参数说明
名称 | 类型 | 必选 | 描述 |
---|
url | String | 是 | 目标服务器 url |
data | Object | 否 | 请求的参数 |
headers | Object | 否 | 设置请求的头部信息 |
错误码说明
error | 描述 |
---|
1 | Error Unknown. |
2 | Connect when already connected. |
3 | Empty URL. |
4 | Illegal URL format. |
5 | URL scheme not ws or wss |
6 | Timed out connecting to server. |
7 | Invalid server certificate. |
8 | Invalid Sec-WebSocket-Accept response. |
9 | Server specified Sec-WebSocket-Protocol that wasn’t requested. |
10 | Invalid State: Cannot send until connection is open. |
11 | Error writing to stream. |
12 | Unable to allocate memory to read from socket. |
代码示例
<script src="https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.inc.min.js"></script>
<style>
.output{ display:block; max-width: 100%; overflow: auto}
.img{ display:block; max-width: 100%; margin: 20px auto;}
</style>
<button id="J_btn_connect" class="btn btn-default">建立链接</button>
<button id="J_btn_send" class="btn btn-default">发送数据</button>
<button id="J_btn_close" class="btn btn-default">关闭链接</button>
<script>
var btnConnect = document.querySelector('#J_btn_connect');
var btnSend = document.querySelector('#J_btn_send');
var btnClose = document.querySelector('#J_btn_close');
var counter = 0;
ap.onSocketOpen(function(){
ap.showToast('socket 已开启');
});
ap.onSocketError(function(){
ap.showToast('socket 出错');
});
ap.onSocketClose(function(){
ap.showToast('socket 已关闭');
});
ap.onSocketMessage(function(res) {
ap.showToast('收到服务器内容:' + res.data)
})
btnConnect.addEventListener('click', function(){
ap.connectSocket({
url: 'ws://127.0.0.1:8088',
data: {
b: '1234567890',
c: 9999
},
headers: {
a: '0987654321'
}
});
});
btnSend.addEventListener('click', function(){
counter ++;
ap.sendSocketMessage({
data: counter+''
}, function(res){
console.warn(res);
});
});
btnClose.addEventListener('click', function(){
counter ++;
ap.closeSocket();
});
</script>