Explanation of websocket instance for WeChat applet development

Source: Internet
Author: User
Why websocket? Traditional real-time interactive games, or server-initiated message sending behaviors (such as push services), if you want to do so, you may use polling, but this consumes too much resources, A large number of requests...

Why websocket?

Traditional real-time interactive games, or server-initiated message sending behaviors (such as push services), if you want to do so, you may use polling, but this consumes too much resources, A large number of requests also increase the burden on the server, and the delay problem is serious. To solve these problems, many teams build their own sockets and use tcp persistent links and custom protocols to interact with the server in real time. A competent team can use this method without any problems. However, a small team may have to spend a lot of time debugging. to solve a lot of problems, the cost is not enough.

H5 introduces webSocket to solve the long link problem on the web page, while small programs also support websocket. This is a very important feature, so this series of articles will come up with a dedicated article to discuss websocket.

WebSocket is essentially a TCP connection, which provides full-duplex data transmission. On the one hand, it can avoid the performance loss caused by frequent connection establishment and disconnection caused by polling, and on the other hand, data can be transmitted in real time in two-way (because it is a long link ), in addition, WebSocket allows cross-origin communication (here there is a potential cross-origin security problem, which must be solved by the server ). Currently, browsers other than IE already support webSocket very well. after a small program is pushed, it will become more popular.

Let's design a new demo, an interesting little game, multi-person version of mine clearance, to be precise, multi-person version of gold mining.

-1 indicates gold. It seems that there is no problem. Next, we need to access webSocket.

(This is a js version. In fact, the map generation scenario is generated in the background. This js version is only a demo, but the algorithm is the same .)

2. we need a server that supports webSocket.

In this example, we use the tornado framework of python (tornado provides the tornado. websocket module ). Of course, you can also use socket. io is a js language server designed for webSocket. it is very easy to use and is compatible with browsers that do not support webSocket (implemented in flash or comet ).

I personally prefer tornado, which has been used for background development for several years. one of the most popular frameworks is tornado, which is a NIO model and very lightweight. for the same rps, java may need-MB of memory, tornado only needs 30-40 M, so hundreds of tornado services can be run on a 4G memory host. java, sorry, can only run three virtual machines. In the era of microservices, this is very important for small companies. Of course, if you are familiar with java, you can try the netty framework.

Another advantage of using tornado for webSocket is that it supports both webSocket and http protocols on the same service (Port. The official demo code of tornado shows how to implement the two protocols at the same time. This can be used in this game: the user enters the home page and uses the http protocol to pull the current room number and data. Because the homepage is the most open, users who enter the homepage may not play games. Therefore, there is no need to establish a webSocket link on the homepage. the webSocket link is mainly used to solve frequent requests and push operations. The homepage has only one request operation. After selecting the room number, go to the next game page and create a webSocket link.

3. client

Using the mini-program development tool, direct connection will report domain name security errors, because the tool has internal restrictions, the security domain name will be allowed to connect. Therefore, here we will continue to change the source code of the tool and change the relevant line as follows:

Find this line of asdebug. js and change it to if (false.

`if (!i(r, "webscoket"))

Readers who are too reluctant to modify can directly use the ide I have cracked. The code for initiating a websocket link is also relatively simple:

`wx.connectSocket({url: webSocketUrl,});
Before calling the request code, add an event listener to check whether the connection is successful:
'

Wx. onSocketOpen (function (res) {console. log ('websocket opened .');});

'Event of connection failure:
wx.onSocketError(function(res){ console.log('websocket fail');}) `

Events triggered when a message is received from the server:

`wx.onSocketMessage(function(res){console.log('received msg: ' + res.data);})
After the link is established, the message sending method is as follows:
'

Message sending

Since creating a link requires several handshakes and takes some time. if the wx. an error will be reported when sendSocketMessage is sent. this is compatible. if the connection is not established successfully, an array is used to save the information to be sent. when the link is set up for the first time, traverse the data and send messages one by one. This logic is encapsulated into a send method as follows:

'Function sendSocketMessage (msg) {if (typeof (msg) === 'object') {// only stringmsg = JSON can be sent. stringify (msg);} if (socketOpened) {// socketOpened variable in wx. set onSocketOpen to truewx. sendSocketMessage ({data: msg});} when else {// is sent, socketMsgQueue has not been set up for the link. push (msg );}}
II. demo function analysis

1. homepage entry

In order to simplify the model and focus on webSocket, we made the homepage into the form of filling in the room number by ourselves. If you have time and ability, you can make the home page into a room list and display the number of people playing in each room. Only one person can go in and play with him. Even the viewing mode can be added later. click another person's room to view others.

3. front-end gold mining

The code is as follows:

Var websocket = require ('.. /.. /websocket/connect. js '); var msgReceived = require ('.. /.. /websocket/msgHandler. js '); Page ({data: {mimeMap: null, leftGolds: 0, // total gold score: 0, // my score roomNo: 0 // room number}, x: 0, // Column y: 0 in the user vertex, // row onLoad: function () {var roomNo = app in the user vertex. getRoomNo (); this. setData ({roomNo: roomNo}); // test // websocket. send ('before connection'); if (! Websocket. socketOpened) {// setMsgReceiveCallback websocket. seteffececallback (msgReceived, this); // connect to the websocket. connect (); websocket. send ({type: 'create'});} else {websocket. send ({type: 'create', no: roomNo}) ;}, digGold: function (event) {// do not directly judge, pass the coordinates to the background for judgment. // if (event.tar get. dataset. value <9) {return;} // Obtain the coordinates of this grid this. x = parseInt(event.tar get. dataset. x); this. y = parseInt(event.tar get. dataset. y); console. log (this. x, this. y); // report the coordinates of this. reportMyChoice () ;}, reportMyChoice: function () {roomNo = app. getRoomNo (); websocket. send ({type: 'Dig', x: this. x, y: this. y, no: roomNo });},});

In the onLoad event of page, update the room number information on the page first. Then we started to focus on websocket. connect to initiate a webSocket link. websocket is our encapsulated module. Then, set the processing logic of msgHandler. js to the callback of the push message on the server. Then, send a create message to create or join the room. The server will respond to the message and return the map scenario data of the room.

DigGold is the click event processing function for each grid. There is a logic here. a grid can contain a maximum of eight grids, so the data size of each grid cannot be greater than 8. the code above shows that there is a 9, this is actually to distinguish it from 0. it is used to represent the data in the lattice that has not been opened on the field. it is represented by 9. of course, you can also use 10,100.

The matrix data binding code of wxml is as follows:

`
 
  {{cell<9?(cell<0?'*':cell):"-"}}
 

4. server implementation

Simply put, because the background is not the focus of this series of articles, although the development of this demo has spent more than half of the time writing the background. The front-end message interaction uses the webSocket channel to transmit the content in the custom format. There is a structure that shows the background code directory, which is relatively random. handlers stores the main processing logic. WebSocketHandler is the entry. in its on_message, it distributes received client messages according to the type, dig type, distribution to answerHandler for processing, create type, distribute to roomHandler for processing.

The background webSocket message processing in this example is also a little different from the traditional http processing process. In the final return, messages are not directly returned, but broadcast messages to all people. For example, if user A clicks on the grid, after the background receives the coordinates, it sends the coordinates and the data in the coordinates together to the people in the room, instead of returning the data to the person who reported the coordinates separately. There is only an isMe field to tell the client whether it is its own operation.

In short, when developing webSocket, the frontend and backend may be different from the traditional http interface development. The reader tries to change his mind when doing a webSocket project.

Note: the websocket link of the applet can only be one globally. The official message is: "A applet can only have one WebSocket connection at the same time. if a WebSocket connection already exists, the connection is automatically closed and a WebSocket connection is created again. "

The above is a detailed explanation of websocket instances for small program development. For more information, see other related articles on php Chinese network!

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.