WeChat mini-app WebSocket explanation and application, websocket explanation

Source: Internet
Author: User

Explanation and Application of mini-program WebSocket and websocket

Mini-program WebSocket

Instance effect:

What I will talk about todayWebSocketInterface and usage in small programs.

WebSocketWhat is it (brief description)

OfWebSocketInterface and HTML5WebSocketBasically the same, the HTTP protocol is upgraded as a newSocketIt 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 notWebSocketThe underlying layer and protocol are described too much, just a little introduction. For more information, seeWebSocketYou can refer to the following: WebSocket Protocol

WebSocket and Ajax Selection

InWebSocketBefore the release, instant messaging is usually used.AjaxAndAjaxReal-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.

WhileWebSocketCan solve the above drawbacks,WebSocketThe 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,WebSocketIs a good choice.

WebSocketProtocol name

WebSocketThe link is nothttpOrhttpsInsteadwsAndwssIt 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.

AddstockPage:

Setwxchart.jsTopages/stock/.

Modifystock.wxml:

stock.jsCode:

// 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! ');})},})

HereWebSocketThe address isws://localhost, Port is12345After the connection is successful, send it to the serverstockThe server then provides the data information to the applet.

WebSocketI 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 PHPWebSocketIt's a little troublesome. You can use Node. js to write about it, and use Node. js to write back-endWebSocketVery convenient.

WebSocket. php code used above: Code download

WebSocketAPI 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)

PassWebSocketTo send data, you must firstwx.connectSocket, Andwx.onSocketOpenThe 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 explainlocalhostIn the above code, I usedlocalhostThe local request is only for placeholder usage, which is not supported in programming.localhostFor 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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.