WeChat Mini Program: WebSocket Application

 

Example content

Today I mainly talk about the interface of WeChat WebSocketand its use in small programs.


WebSocketwhat is (briefly)

The interface of WeChat WebSocketis basically the same as that of HTML5. WebSocketIt is upgraded from the HTTP protocol. As a new one Socket, it is used in B/S. It realizes full-duplex communication between the browser and the server.

Because this is a small program, I will not WebSocketexplain too much about the bottom layer and protocol, but I will introduce it a little. For details, WebSocketplease refer to the following:

WebSocket Protocol


WebSocketAjax choice with

Before WebSocketit comes out, the realization of instant messaging is usually achievedAjax by using the method of polling to obtain real-time data. Polling is to make HTTP requests to obtain data within a specified time interval, and this method will cause some drawbacks. Ajax, on the one hand, it generates too many HTTP requests, occupies bandwidth, increases the response of the server, and wastes resources. On the other hand, because not every request will have data changes (like a chat room), it will cause the utilization of requests Low.

And WebSocketjust to solve the above drawbacks, WebSocketthe client and the server specially establish a channel before, the request is only requested once, and the server data can be obtained in real time from the same channel, so when applied to real-time applications, it WebSocketis a very important Nice choice.


WebSocketprotocol name

WebSocketThe link does not start with httpor https, but starts with wsand wss, which needs to be noted here.


Example: Real-time display of transaction information

This is similar to viewing stock information in real time, and the chart plugin is used here wxchart.

wxchart plugin address: plugin download

That's basically it, let's get started.

Add stockpages:

will be wxchart.jsplaced pages/stock/in.

Edit stock.wxml:

stock.js code:

// pages/stock/stock.js
 // Load plugin 
var wxCharts = require( ' wxcharts.js ' );

Page({
  data: {},

  onLoad: function (options) {

    // establish a connection 
    wx.connectSocket({
      url: "ws://localhost:12345",
    })

    // The connection is successful 
    wx.onSocketOpen(function() {
      wx.sendSocketMessage({
        data: 'stock',
      })
    })

    // Receive data 
    wx.onSocketMessage(function(data) {
       var objData = JSON.parse(data.data);
      console.log(data);
        new wxCharts({
          canvasId: 'lineCanvas',//指定canvas的id
          animation: false,
          type: ' line ' , // type is line graph 
          categories: [ ' 2012 ' , ' 2013 ' , ' 2014 ' , ' 2015 ' , ' 2016 ' , ' 2017 ' ],

          series: [{
            name: ' trading volume ' ,
            data: objData, // data received by websocket 
            format: function (val) {
               if ( typeof val == " string " ) {
                val = parseFloat(val);
              }
              return val.toFixed( 2 ) + ' million ' ;
            }
          },
          ],
          yAxis: {
            title: ' Transaction amount (ten thousand yuan) ' ,
            format: function (val) {
              return val.toFixed(2);
            },
            min: 0
          },
          width: 320,
          height: 200
        });      
    })

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

 

 

这里WebSocket的地址是ws://localhost,端口是12345,连接成功后,向服务器发送stock,然后服务器向小程序提供数据信息。

WebSocket的服务器端我是用PHP写的,这里贴一下,大家可以参考一下:

<?php
include 'WebSocket.php';

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 == 'stock') {
                        $arr = array();

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

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

$s = new WebSocket2('localhost', 12345);
$s -> run();

 

用PHP写WebSocket稍微有些麻烦,懂Node.js的可用Node.js写一下,Node.js写后端的WebSocket很方便。

上面用到的WebSocket.php代码:代码下载

实例效果:


微信WebSocketAPI参数说明

wx.connectSocket(OBJECT)

参数 类型 必填 说明
url String 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
data Object 请求的数据
header Object HTTP Header , header 中不能设置 Referer
method String 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

wx.onSocketOpen(CALLBACK)

监听WebSocket连接打开事件。

wx.onSocketError(CALLBACK)

监听WebSocket错误。

wx.sendSocketMessage(OBJECT)

通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。

参数 类型 必填 说明
data String/ArrayBuffer 需要发送的内容
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

wx.onSocketMessage(CALLBACK)

监听WebSocket接受到服务器的消息事件。

参数 类型 说明
data String/ArrayBuffer 服务器返回的消息

wx.closeSocket()

关闭WebSocket连接。

wx.onSocketClose(CALLBACK)

监听WebSocket关闭。


关于localhost

这里说明一下localhost,上述代码中我用到了localhost的本地请求,这里只是占位使用,在程序编写中是不支持localhost本地请求的,这里大家要注意一下。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324930111&siteId=291194637