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

May 10, 2018 pm 03:52 PM
WeChat applet

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!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu WeChat mini program officially launched

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

What is the name of Xianyu WeChat applet?

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements image upload function

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

Implement the drop-down menu effect in WeChat applet

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use WeChat applet to achieve carousel switching effect

How to use PHP to develop the second-hand transaction function of WeChat applet? How to use PHP to develop the second-hand transaction function of WeChat applet? Oct 27, 2023 pm 05:15 PM

How to use PHP to develop the second-hand transaction function of WeChat applet?

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implement image filter effects in WeChat mini programs

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

Implement image rotation effect in WeChat applet

See all articles