Alipay JSSDK V3.1.1

ap.connectSocket(OPTION | url, CALLBACK)

向指定服务器发起 WebSocket 连接请求。可直接传入一个字符串作为 OPTION.url 参数。

OPTION 参数说明

名称类型必选描述
urlString目标服务器 url
dataObject请求的参数
headersObject设置请求的头部信息

错误码说明

error描述
1Error Unknown.
2Connect when already connected.
3Empty URL.
4Illegal URL format.
5URL scheme not ws or wss
6Timed out connecting to server.
7Invalid server certificate.
8Invalid Sec-WebSocket-Accept response.
9Server specified Sec-WebSocket-Protocol that wasn’t requested.
10Invalid State: Cannot send until connection is open.
11Error writing to stream.
12Unable 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>