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
// 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
代码:代码下载
实例效果:
微信WebSocket
API参数说明
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
本地请求的,这里大家要注意一下。