🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# wx.connectSocket ### SocketTask wx.connectSocket(Object object) 创建一个 WebSocket 连接。使用前请注意阅读[相关说明](https://developers.weixin.qq.com/minigame/dev/tutorial/ability/network.html)。 #### 参数 ##### Object object 属性类型默认值是否必填说明支持版本urlstring是开发者服务器 wss 接口地址headerObject否HTTP Header,Header 中不能设置 RefererprotocolsArray.<string>否子协议数组>= 1.4.0successfunction否接口调用成功的回调函数failfunction否接口调用失败的回调函数completefunction否接口调用结束的回调函数(调用成功、失败都会执行)#### 返回值 ##### SocketTask > 支持版本 >= 1.7.0 WebSocket 任务 #### 并发数 - 1.7.0 及以上版本,最多可以同时存在 5(小游戏)/2(小程序)个 WebSocket 连接。 - 1.7.0 以下版本,一个小程序同时只能有一个 WebSocket 连接,如果当前已存在一个 WebSocket 连接,会自动关闭该连接,并重新创建一个 WebSocket 连接。#### 示例代码 ``` <pre class="prettyprint"><ol class="linenums"><li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln">wx</span><span class="pun">.</span><span class="pln">connectSocket</span><span class="pun">({</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> url</span><span class="pun">:</span><span class="pln"> </span><span class="str">'wss://example.qq.com'</span><span class="pun">,</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> data</span><span class="pun">:{</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> x</span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span><span class="pun">,</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> y</span><span class="pun">:</span><span class="pln"> </span><span class="str">''</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> </span><span class="pun">},</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> header</span><span class="pun">:{</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> </span><span class="str">'content-type'</span><span class="pun">:</span><span class="pln"> </span><span class="str">'application/json'</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> </span><span class="pun">},</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> protocols</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="str">'protocol1'</span><span class="pun">],</span></code></li> <li class="l"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pln"> method</span><span class="pun">:</span><span class="str">"GET"</span></code></li> <li class="l1"><code class="pcalibre9 pcalibre8 pcalibre7"><span class="pun">})</span></code></li> </ol> ``` > 原文: <https://developers.weixin.qq.com/minigame/dev/api/network/websocket/wx.connectSocket.html>