wx.connectSocket:与服务端创建链接javascript
wx.sendSocketMessage:向服务端发送数据php
wx.closeSocket:关闭链接html
wx.onSocketOpen:成功与服务端创建链接后触发的事件java
wx.onSocketError:与服务端创建链接失败后触发的事件web
wx.onSocketMessage:服务端返回响应消息后触发的事件json
wx.onSocketClose:成功关闭WebSocket链接后触发的事件小程序
url:String类型,必选,开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名浏览器
data:Object类型,可选,请求的数据服务器
header:Object类型,可选,HTTPS Header , header 中不能设置 Referer微信
method: String类型,可选,默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success:Function类型,可选,接口调用成功的回调函数
fail:Function 类型,可选,接口调用失败的回调函数
complete:Function类型,可选, 接口调用结束的回调函数(调用成功、失败都会执行)
data:String或ArrayBuffer类型,必选,须要发送的内容
success:Function类型,可选,接口调用成功的回调函数
fail:Function 类型,可选,接口调用失败的回调函数
complete:Function类型,可选, 接口调用结束的回调函数(调用成功、失败都会执行)
var socketOpen = falsevar socketMsgQueue = []wx.connectSocket({ url: 'wss://example.com/test.php', // 该Url并不存在,只是为了演示假设了一个url data:{ x: '', y: '' }, header:{ 'content-type': 'application/json' }, method:"GET"})// 成功创建WebSocket链接后,会调用该函数wx.onSocketOpen(function(res) { socketOpen = true for (var i = 0; i < socketMsgQueue.length; i++){ sendSocketMessage(socketMsgQueue[i]) } socketMsgQueue = []})// 向服务端发送数据,若是成功创建了链接,则直接发送,不然保存到消息队列(socketMsgQueue)中function sendSocketMessage(msg) { if (socketOpen) { wx.sendSocketMessage({ data:msg }) } else { socketMsgQueue.push(msg) }}// 接收服务端的响应消息,而后关闭WebSocket链接wx.onSocketMessage(function(res) { console.log('收到服务器内容:' + res.data) wx.closeSocket()})// 成功关闭WebSocket链接后,会调用该函数wx.onSocketClose(function(res) { console.log('WebSocket 已关闭!')})
<html> <head> <title>测试WebSocket</title> <script> function init() { websocket = new WebSocket("ws://echo.websocket.org/"); websocket.onopen = function() { document.getElementById("output").innerHTML += "<p>> CONNECTED</p>"; }; websocket.onmessage = function(evt){ document.getElementById("output").innerHTML += "<p style='color: blue;'>> RESPONSE: " + evt.data + "</p>"; }; websocket.onerror = function(evt){ document.getElementById("output").innerHTML += "<p style='color: red;'>> ERROR: " + evt.data + "</p>"; }; } function sendMessage(message) { document.getElementById("output").innerHTML += "<p>> SENT: " + message + "</p>"; websocket.send(message); } window.addEventListener("load", init, false);</script> </head> <body> <input onkeypress="if(this.value) {if (window.event.keyCode == 13) { sendMessage(this.value); this.value = null; }}"/> <div id="output"></div> </body></html>
本文分享自微信公众号 - 极客起源(geekculture)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。