https://blog.csdn.net/lecepin/article/details/54632749
Example content
Today I mainly talk about the interface of WeChat WebSocket
and its use in small programs.
WebSocket
what is (briefly)
The interface of WeChat WebSocket
is basically the same as that of HTML5. WebSocket
It 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 WebSocket
explain too much about the bottom layer and protocol, but I will introduce it a little. For details, WebSocket
please refer to the following:
WebSocket
Ajax
choice with
Before WebSocket
it 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 WebSocket
just to solve the above drawbacks, WebSocket
the 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 WebSocket
is a very important Nice choice.
WebSocket
protocol name
WebSocket
The link does not start with http
or https
, but starts with ws
and 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 stock
pages:
will be wxchart.js
placed pages/stock/
in.
Edit stock.wxml
:
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连接失败!'); }) }, })
WebSocket
The address here is ws://localhost
, the port is 12345
, after the connection is successful, send it to the server stock
, and then the server provides data information to the applet.
WebSocket
I wrote the server side in PHP, here is a post for your reference:
<?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();
WebSocket
It is a little troublesome to write in PHP . If you know Node.js, you can write it in Node.js. Node.js is WebSocket
very convenient to write the backend.
The code used above
WebSocket.php
: code download
Example effect:
WeChat WebSocket
API parameter description
wx.connectSocket(OBJECT)
parameter | Types of | Required | illustrate |
---|---|---|---|
url | String | Yes | Developer server interface address, must be wss protocol, and the domain name must be a legal domain name configured in the background |
data | Object | no | requested data |
header | Object | no | HTTP Header , the Referer cannot be set in the header |
method | String | no | Default is GET, valid values are: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT |
success | Function | no | Callback function for successful interface call |
fail | Function | no | Callback function for interface call failure |
complete | Function | no | The callback function of the end of the interface call (the call will be executed if it succeeds or fails) |
wx.onSocketOpen(CALLBACK)
Listen for WebSocket connection open events.
wx.onSocketError(CALLBACK)
Listen for WebSocket errors.
wx.sendSocketMessage(OBJECT)
WebSocket
Sending data over a connection needs to be done first wx.connectSocket
and after the wx.onSocketOpen
callback.
parameter | Types of | Required | illustrate |
---|---|---|---|
data | String/ArrayBuffer | Yes | what needs to be sent |
success | Function | no | Callback function for successful interface call |
fail | Function | no | Callback function for interface call failure |
complete | Function | no | The callback function of the end of the interface call (the call will be executed if it succeeds or fails) |
wx.onSocketMessage(CALLBACK)
Listen to the WebSocket receiving the message event from the server.
parameter | Types of | illustrate |
---|---|---|
data | String/ArrayBuffer | message returned by the server |
wx.closeSocket()
Close the WebSocket connection.
wx.onSocketClose(CALLBACK)
Listen for WebSocket closures.
aboutlocalhost
Here is an explanation . The local request localhost
I used in the above code is localhost
only used here as a placeholder. localhost
Local requests are not supported in program writing. Everyone should pay attention here.