ap.closeSocket 关闭 WebSocket 连接
优质
小牛编辑
132浏览
2023-12-01
ap.closeSocket()
关闭 WebSocket 连接。
代码示例
<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 class="btn btn-default">建立链接</button>
<button class="btn btn-default">发送数据</button>
<button 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>