In the above article, we have noticed that the message in the applet developer tool is sent and received by webSocket protocol. Of course, this is not said in a thin air, but in the applet logic layer appService.js source code, there is a code indicating that the message format and part of it I have not listed. For example, its data analysis and some message formats reported to their own servers need to be focused on first.
So I’m going to show you the process and I’m going to find appService.jsYou can see the link address, part of the code for sending and receiving data, I have folded part of the code due to the size of the image, you can have a closer look.
I would like to brief some knowledge of Webstocket first, maybe some students are not very familiar with this aspect. The details of webstocket content will not be described in this article, but will be covered in a later article.
What is the websocket
There’s a lot of stuff that you can look up in Google, but do you really understand whether you can design it flexibly in your own projects or just use the documentation API, or do you have to explore it a little bit more.
The following figure forWebstockrt agreement:
The WebSocket protocol allows two-way communication between a user agent running untrusted code in a controlled environment and a remote host that has chosen to communicate from that code. A simple description is that there is a persistent connection between the client and the server, and both can send data to each other anytime, anywhere
Why websocket
A new specification or a new technology must be born to solve or improve the shortcomings of the previous solution so that progress can continue.
Before there was no Websocket, we used HTTP very well. However, with the requirements of some applications, such as chat, stock games, which have high requirements for real-time data, sending data using HTTP protocol can only be unilaterally requested by the client, and the server responds to obtain the latest data. If the data of the server is changed quickly, such as the information of the stock, so it can only be periodically requested, there will be low efficiency and waste of resources and data is not real-time synchronization, in order to solve these problems through the study of Websocket protocol shine.
Some advantages of WebSocket:
- Support two-way communication, with strong real-time
- Binary support is friendly
- Compared with HTTP protocol control overhead is much less
- Users can freely extend the protocol and customize sub-protocols such as (WSS).
How to use Websocket
This point is more extensive, the generation of a new solution and new technology will go through the process of development from shallow to deep, mainly look at the specific design and use of the big door, the following some links can let you first understand the concept and basic use, this chapter is not derived from more websocket related content.
(If you are interested in learning more about Websocket, please pay attention to my webSocket column.)
- webStocket Api
- [MDN]
- You can try this Websocket demo if you want to test it online
This is a relatively simple online to see the effect of the web page
If you want to try it yourself, I have written a simplified case of server and client in my Github repository, with a total of more than 10 lines of code, which is convenient. If you are interested, you can check the case address
The result of executing index.js is as follows:
The following content I will combine in the implementation of this small program running environment for some of the use of Websocket design and part of the code display.
Back to the main point, we added some log saving in the source code of appservice.js where it is sent and received. Make sure to exit the tool process completely before opening it otherwise it will not work.
Then we re-enter the developer tools and open a small application project. I opened an official cloud development project example as you can see:
From this picture, we can see some information. Let me give you a brief introduction:
Data transmission section
send===>{"command":"APPSERVICE_INVOKE"."data": {"api":"operateWXData"."args": {"data": {"api_name":"qbase_commapi"."data": {"qbase_api_name":"tcbapi_init"."qbase_req":"{\"trace_user\":true}"."qbase_options": {},"qbase_meta": {"session_id":"1587696384156"."sdk_version":"Wx - miniprogram - SDK / 2.9.5 (1578926697000)"},"cli_req_id":"1587696386661 _0. 5287857917854695"},"operate_directly":false},"isImportant":false."requestInQueue":false."apiName":"qbase_commapi"."reqData": {"qbase_api_name":"tcbapi_init"."qbase_req":"{\"trace_user\":true}"."qbase_options": {},"qbase_meta": {"session_id":"1587696384156"."sdk_version":"Wx - miniprogram - SDK / 2.9.5 (1578926697000)"},"cli_req_id":"1587696386661 _0. 5287857917854695"}},"callbackID":20}}
Copy the code
Some fields and objects can be observed. (This is an example of a normal cloud development project when it is opened by default.
- command
- data
- api
- args
- data
- api_name
- qbase_api_name
- qbase_req
- data
- callbackID
So if you look at this API operateWXData that you’re probably not familiar with, because it’s an API that wechat doesn’t use externally but internally, that’s not what we’re going to focus on right now, what we’re going to describe is webstocket, As for the IMPLEMENTATION of API will be in the following how to implement small program external API to describe, we here as long as we know his message transmission format can be.
- Command message type
- Data Various data combinations
- CallbackID indicates that this is important
Data receiving part
<====12receive {"command":"APPSERVICE_INVOKE_CALLBACK"."data": {"callbackID":20."res": {"errMsg":"operateWXData:ok"."data": {"data":"{\"baseresponse\":{\"errcode\":0,\"stat\":{\"qbase_cost_time\":141}},\"tcb_api_list\":[{\"apiname\":\"tcbapi_db_adddocu ment\",\"status\":1},{\"apiname\":\"tcbapi_callfunction\",\"status\":1},{\"apiname\":\"tcbapi_component_gettempfileurl\" ,\"status\":1},{\"apiname\":\"tcbapi_db_countdocument\",\"status\":1},{\"apiname\":\"tcbapi_db_deletedocument\",\"status \":1},{\"apiname\":\"tcbapi_deletefile\",\"status\":1},{\"apiname\":\"tcbapi_downloadfile\",\"status\":1},{\"apiname\":\ "tcbapi_gettempfileurl\",\"status\":1},{\"apiname\":\"tcbapi_db_querydocument\",\"status\":1},{\"apiname\":\"tcbapi_db_s etdocument\",\"status\":1},{\"apiname\":\"tcbapi_slowcallfunction\",\"status\":1},{\"apiname\":\"tcbapi_slowcallfunction _v2\",\"status\":1},{\"apiname\":\"tcbapi_traceuser\",\"status\":1},{\"apiname\":\"tcbapi_uploadfile\",\"status\":1},{\" apiname\":\"tcbapi_db_updatedocument\",\"status\":1},{\"apiname\":\"tcbapi_init\",\"status\":1}],\"config\":{\"db_doc_si ze_limit\":524288,\"upload_max_file_size\":52428800,\"get_temp_file_url_max_requests\":50,\"call_function_poll_max_retry \":10,\"call_function_max_req_data_size\":5242880,\"call_function_client_poll_timeout\":15000,\"call_function_valid_star t_retry_gap\":100000}}"}}}}
Copy the code
By contrast, we can see what is said in the core part above:
send===> "command":"APPSERVICE_INVOKE" "callbackID":20
receive===>"command":"APPSERVICE_INVOKE_CALLBACK" "callbackID":20
Copy the code
The message type for APPSERVICE_INVOKE is sent by the Service layer to the Service for receiving processing
Code to achieve the browser running environment Websocket service communication design
The node mode is used to start the service to create a server:
const ws = require('ws');
const EventEmitter = require('events');
class SocketServer extends EventEmitter {
constructor (options) {
super(a);this.port = options.port;
this.wss = new ws.Server({ port: this.port });
this.socketClientMap = new SocketClientMap();
}
async start () {
this.wss.on('connection'.ws= > {
this.socketClientMap.addSocketClient(ws);
ws.on('close'.() = > {
this.socketClientMap.removeSocketClient(ws.protocol);
});
ws.on('message'.async message => {
await this.handle(message);
});
});
this.on(SEND_MSG_TO_CONTROLLER, (message) = > {
this.sendMessageToController(message);
});
this.on(SEND_MSG_TO_SPECIAL_WEBVIEW, ({ webviewId, message }) = > {
this.sendMessageToSpecialWebview(webviewId, message);
});
this.running = true;
}}
Copy the code
Create client links to send and receive:
const WebSocket = require('ws');
class SocketClient {
constructor (ws) {
this.ws = ws;
this.msgQueue = [];
}
setWebSocket (ws) {
this.ws = ws;
this.msgQueue.forEach(msg= > {
this.ws.send(JSON.stringify(msg));
});
this.msgQueue = [];
}
removeWebSocket () {
this.ws = null;
}
send (msg) {
if (!this.ws || this.ws.readyState ! == WebSocket.OPEN) {this.msgQueue.push(msg);
} else {
this.ws.send(JSON.stringify(msg)); }}}Copy the code
The above two class files are relatively simple service and client creation. Here we create a Client collection class:
class SocketClientMap {
constructor () {
this.socketClients = new Map(a); } addSocketClient (ws) {let socketClient = this.socketClients.get(ws.protocol);
if(! socketClient) { socketClient =new SocketClient(ws);
} else {
socketClient.setWebSocket(ws);
}
this.socketClients.set(ws.protocol, socketClient);
}
getSocketClient (protocol) {
let socketClient = this.socketClients.get(protocol);
if(! socketClient) { socketClient =new SocketClient(protocol);
this.socketClients.set(protocol, socketClient);
}
return socketClient;
}
removeSocketClient (protocol) {
this.socketClients.delete(protocol);
}
loop (cb) {
this.socketClients.forEach((value, key) = >cb(value, key)); }};Copy the code
A newly added addSocketClient method
If SocketClient does not exist, create a new SocketClient based on WS. Otherwise, replace the old WS with the new WS. In this way, messages in the message queue can be sent to the new WS immediately after replacement, ensuring availability.
GetSocketClient method
Calling this function always returns a SocketClient instance so that the user can send messages at any time.
The above article mainly focuses on the format and content composition of the message and the order of several receivers and sender. In the next part, I will describe the specific process by using specific codes through several commonly used external APIS.
The author of this article: The author of the death of the wind public number: small wind north blogger reprinted after obtaining authorization. If you need to reprint please contact the blogger to obtain authorization.