Home > WeChat Applet > Mini Program Development > WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing

WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing

高洛峰
Release: 2018-05-10 15:52:53
Original
5814 people have browsed it

This article describes the WeChat applet WebSocket protocol description and usage examples, using examples to help us quickly become familiar with and use it.

What is WebSocket (brief description)
WeChat’s WebSocket interface is basically the same as HTML5’s WebSocket. It is an upgrade from the HTTP protocol. As a new Socket, it is used in B/S Used on the Internet, it realizes full-duplex communication between the browser and the server.
Because this is a small program, I won’t explain too much about the underlying layer and protocol of WebSocket, just a brief introduction. If you want to know more about WebSocket, you can refer to the following:

WebSocket Protocol

Selection of WebSocket and Ajax

Before WebSocket came out, instant messaging was usually used Ajax is implemented, and Ajax obtains real-time data through polling. Polling is to perform HTTP requests to obtain data within a specified time interval. However, this method will cause some disadvantages. On the one hand, it will generate too many HTTP requests occupy bandwidth, increase the response of the server, and waste resources. On the other hand, because not every request will have data changes (just like a chat room), it will cause low utilization of requests.
WebSocket can just solve the above drawbacks. WebSocket establishes a channel between the client and the server. The request is only requested once, and the server's data can be obtained in real time from the same channel, so when applied to real-time applications When using WebSocket, WebSocket is a very good choice.

WebSocket protocol name

The WebSocket link does not start with http or https, but starts with ws and wss. You need to pay attention here.
Example: Real-time display of trading information

This is similar to viewing stock information in real time. The chart plug-in wxchart is used here.

wxchart plug-in address:

That’s basically it, let’s officially start.
Add stock page:
WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing

Put wxchart.js into pages/stock/.
Modify stock.wxml:
WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing

stock.js code:

// pages/stock/stock.js
//加载插件
var wxCharts = require('wxcharts.js');

Page({
  data: {},

  onLoad: function (options) {

    //建立连接
    wx.connectSocket({
      url: "ws://localhost:12345",
    })

    //连接成功
    wx.onSocketOpen(function() {
      wx.sendSocketMessage({
        data: 'stock',
      })
    })

    //接收数据
    wx.onSocketMessage(function(data) {
      var objData = JSON.parse(data.data);
      console.log(data);
        new wxCharts({
          canvasId: 'lineCanvas',//指定canvas的id
          animation: false,
          type: 'line',//类型是线形图
          categories: ['2012', '2013', '2014', '2015', '2016', '2017'],

          series: [{
            name: '交易量',
            data: objData,//websocket接收到的数据
            format: function (val) {
              if (typeof val == "string") {
                val = parseFloat(val);
              }
              return val.toFixed(2) + '万元';
            }
          },
          ],
          yAxis: {
            title: '交易金额 (万元)',
            format: function (val) {
              return val.toFixed(2);
            },
            min: 0
          },
          width: 320,
          height: 200
        });      
    })

    //连接失败
    wx.onSocketError(function() {
      console.log('websocket连接失败!');
    })
  },
})
Copy after login



The address of WebSocket here is ws://localhost, port It is 12345. After the connection is successful, stock is sent to the server, and then the server provides data information to the mini program.
I wrote the server side of WebSocket in PHP. I will post it here for your reference:

<?php
include &#39;WebSocket.php&#39;;

class WebSocket2 extends WebSocket{
    public function run(){
          while(true){
          $socketArr = $this->sockets;
          $write = NULL;
          $except = NULL;
          socket_select($socketArr, $write, $except, NULL);
          foreach ($socketArr as $socket){
            if ($socket == $this->master){
              $client = socket_accept($this->master);
              if ($client < 0){
                $this->log("socket_accept() failed");
                continue;
              }else{
                $this->connect($client);
              }
            }
            else{
              $this->log("----------New Frame Start-------");
              $bytes = @socket_recv($socket,$buffer,2048,0);
              if ($bytes == 0){
                $this->disconnect($socket);
              }else{
                $user = $this->getUserBySocket($socket);
                if (!$user->handshake){
                  $this->doHandShake($user, $buffer);
                }else{
                    $buffer = $this->unwrap($user->socket, $buffer);

                    //请求为stock时,向通道内推送数据
                    if ($buffer == &#39;stock&#39;) {
                        $arr = array();

                        //模拟数据
                        for ($i=0; $i < 6; $i++) { 
                            $arr[] = rand(1, 100) / 100;
                        }

                        $this->send($user->socket, json_encode($arr));
                    }
                }
              }
            }
          }
        }
    }
}

$s = new WebSocket2(&#39;localhost&#39;, 12345);
$s -> run();
Copy after login

It is a little troublesome to write WebSocket in PHP. Those who know Node.js can write it in Node.js. Node.js is very convenient to write back-end WebSocket.

Example effect:

WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing
WeChat WebSocketAPI parameter description

##wx.connectSocket(OBJECT)
[tr] Required description of parameter type[/tr]

urlString isThe developer server interface address must be wss protocol, and the domain name must be the legal domain name configured in the background dataObjectNo Requested dataheaderObjectNoHTTP Header, Referer cannot be set in header methodStringNoThe default is GET, valid values ​​are: OPTIONS, GET, HEAD, POST, PUT , DELETE, TRACE, CONNECTsuccessFunctionNoCallback function for successful interface callfailFunctionNoCallback function for failure of interface callcompleteFunctionNoThe callback function at the end of the interface call (will be executed if the call is successful or failed)

wx.onSocketOpen(CALLBACK)

Listen to the WebSocket connection open event.
wx.onSocketError(CALLBACK)

Listen for WebSocket errors.
wx.sendSocketMessage(OBJECT)

To send data through a WebSocket connection, you need to wx.connectSocket first, and then send it after the wx.onSocketOpen callback.
[tr] Required description of parameter type[/tr]

data String/ArrayBuffer is Content to be sent
success Function No Callback function for successful interface call
fail Function No Callback function for failure of interface call
complete Function No The callback function at the end of the interface call (will be executed if the call is successful or failed)

wx.onSocketMessage(CALLBACK)

Listen to the message event that WebSocket receives from the server.
[tr] Parameter type description[/tr]

data String/ArrayBuffer Message returned by the server

wx.closeSocket()
Close the WebSocket connection.
wx.onSocketClose(CALLBACK)
Listen to WebSocket closing.
About localhost
Here is a description of localhost. In the above code, I used the local request of localhost. This is just a placeholder. Localhost local requests are not supported in program writing. Here everyone Pay attention.

The above is the detailed content of WeChat Mini Program WebSocket Protocol Description and Usage Example Sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template