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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

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

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

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

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

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

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

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

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

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

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

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

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles