Explanation and Application of mini-program WebSocket and websocket
Mini-program WebSocket
Instance effect:
What I will talk about todayWebSocket
Interface and usage in small programs.
WebSocket
What is it (brief description)
OfWebSocket
Interface and HTML5WebSocket
Basically the same, the HTTP protocol is upgraded as a newSocket
It is used on B/S to implement full duplex communication between the browser and the server.
This is because it is a small program, so it is notWebSocket
The underlying layer and protocol are described too much, just a little introduction. For more information, seeWebSocket
You can refer to the following: WebSocket Protocol
WebSocket and Ajax Selection
InWebSocket
Before the release, instant messaging is usually used.Ajax
AndAjax
Real-time data is obtained through round-robin. Round-Robin is used to obtain data through HTTP requests within a specified time interval. This method has some drawbacks, on the one hand, too many HTTP requests are generated, the bandwidth is occupied, the server is increased, and resources are wasted. On the other hand, not every request will have data changes (like chatting rooms ), therefore, the request utilization rate is low.
WhileWebSocket
Can solve the above drawbacks,WebSocket
The client and the server have previously set up a dedicated channel, and the request is only one request, and the server data can be obtained in real time from the same channel. Therefore, when applied to real-time applications,WebSocket
Is a good choice.
WebSocket
Protocol name
WebSocket
The link is nothttp
Orhttps
Insteadws
Andwss
It must be noted here.
Instance: displays transaction information in real time.
This is similar to viewing stock information in real time. Here we use the chart plug-in wxchart: wxchart plug-in address: Download the plug-in.
This is basically the beginning.
Addstock
Page:
Setwxchart.js
Topages/stock/
.
Modifystock.wxml
:
stock.js
Code:
// Pages/stock. js // load the 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',})} // receives the wx data. onSocketMessage (function (data) {var objData = JSON. parse (data. data); console. log (data); new wxCharts ({canvasId: 'linecanca', // specify the canvas id Animation: false, type: 'line', // The type is a linear chart categories: ['20170101', '20160301', '20160301', '20160301 ', '000000'], series: [{name: 'transaction volume ', data: objData, // the data format: function (val) received by websocket) {if (typeof val = "string") {val = parseFloat (val);} return val. toFixed (2) + '10 thousand yuan ';}},], yAxis: {title: 'transaction amount (10 thousand yuan)', format: function (val) {return val. toFixed (2) ;}, min: 0}, width: 320, height: 200 });})// Connection Failed wx. onSocketError (function () {console. log ('websocket connection failed! ');})},})
HereWebSocket
The address isws://localhost
, Port is12345
After the connection is successful, send it to the serverstock
The server then provides the data information to the applet.
WebSocket
I wrote it in PHP on the server side. Here I post it for your reference:
<? Phpinclude 'websocket. php'; class WebSocket2 extends WebSocket {public function run () {while (true) {$ socketArr = $ this-> sockets; $ write = NULL; $ Login T = NULL; socket_select ($ socketArr, $ write, $ response T, 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); // if ($ buffer = 'stock') {$ arr = array (); // simulate data 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 ();
Written in PHPWebSocket
It's a little troublesome. You can use Node. js to write about it, and use Node. js to write back-endWebSocket
Very convenient.
WebSocket. php code used above: Code download
WebSocket
API parameter descriptionwx.connectSocket(OBJECT)
Parameters |
Type |
Required |
Description |
Url |
String |
Yes |
The developer server interface address, which must be a wss protocol and a valid domain name configured in the background |
Data |
Object |
No |
Requested Data |
Header |
Object |
No |
The Referer cannot be set in the HTTP Header. |
Method |
String |
No |
The default value is GET. Valid values include OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT. |
Success |
Function |
No |
Callback Function for successful API call |
Fail |
Function |
No |
Callback Function for interface call failure |
Complete |
Function |
No |
The callback function after the interface call ends. (The callback function is executed if the call succeeds or fails) |
wx.onSocketOpen(CALLBACK)
Listen to WebSocket connection opening events.
wx.onSocketError(CALLBACK)
An error occurred while listening to WebSocket.
wx.sendSocketMessage(OBJECT)
PassWebSocket
To send data, you must firstwx.connectSocket
, Andwx.onSocketOpen
The message can be sent only after callback.
Parameters |
Type |
Required |
Description |
Data |
String/ArrayBuffer |
Yes |
Content to be sent |
Success |
Function |
No |
Callback Function for successful API call |
Fail |
Function |
No |
Callback Function for interface call failure |
Complete |
Function |
No |
The callback function after the interface call ends. (The callback function is executed if the call succeeds or fails) |
Listen to WebSocket to receive message events from the server.
Parameters |
Type |
Description |
Data |
String/ArrayBuffer |
Message returned by the server |
Disable WebSocket connection.
wx.onSocketClose(CALLBACK)
Disable WebSocket listening.
Aboutlocalhost
Here we will explainlocalhost
In the above code, I usedlocalhost
The local request is only for placeholder usage, which is not supported in programming.localhost
For local requests, pay attention to them here.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!