In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to apply Mini Program WebSocket long connection". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to apply Mini Program WebSocket long connection".
The architecture of Mini Program is very simple, there are two network synchronization, one is the HTTPS channel, which is used for regular requests. For WebSocket requests, it will first go to HTTPS and then switch the protocol to WebSocket's TCP connection, thus achieving full-duplex communication.
1. Prepare domain names and certificates
In WeChat Mini Programs, all network requests are strictly restricted, and domain names and protocols that do not meet the requirements cannot be requested, including:
You are only allowed to communicate with domain names configured in MP. If you do not already have a domain name, you need to register one.
The network request must follow the HTTPS protocol, so you also need to apply for a certificate for your domain name.
After the domain name is registered, you can log in to Wechat public platform to configure the communication domain name.
two。 Deployment of CVM and image
The server running code and configuration of rock and paper scissors have been packaged into a Tencent Cloud CVM image, which you can use directly.
Tencent Cloud users can receive gift packages for free to experience the Tencent Cloud Mini Program solution.
After the image deployment is completed, the basic environment, code, and configuration for running the WebSocket service will be available on the CVM.
The image already contains the server environment and code of two Mini Program, "rock paper scissors" and "small photo album". Friends who need to experience two Mini Program do not need to deploy repeatedly.
3. Configure HTTPS
Nginx has been deployed in the image, and the domain name, certificate and private key in the configuration need to be modified under / etc/nginx/conf.d.
After the configuration is complete, you can start nginx.
Nginx
4. Domain name resolution
We also need to add domain name records for resolution to our CVM, so that we can use domain names for HTTPS services.
For domain names registered with Tencent Cloud, you can directly use the Cloud Resolution console to add host records and directly select the CVM purchased above.
After the resolution takes effect, we can use the domain name in the browser for HTTPS access.
5. Start the WebSocket service
In the nginx configuration of the mirror (/ etc/nginx/conf.d), the request for / applet/websocket has been forwarded to http://127.0.0.1:9595 for processing. We need to run the WebSocket service implemented by Node on this port.
Enter the source code location in the image:
Cd / data/release/qcloud-applet-websocket
Copy the code
Start the service using pm2:
Pm2 start process.json
Copy the code
6. Start WeChat Mini Programs
Modify the config.js configuration in the Wechat source code in the Mini Program developer tool to change the communication domain name to the domain name applied above. Click debug after completion to connect to the WebSocket service to play the game.
After the configuration is complete, you can see the prompt of successful construction by running Mini Program!
Why use WebSocket?
Traditional HTTP polling or persistent connection can also achieve the same effect as server push, but these methods have some problems such as excessive resource consumption or push delay. WebSocket directly uses TCP connections to maintain full-duplex transmission, which can effectively reduce the establishment of connections and achieve real server communication, which is a good choice for applications with low latency and requirements.
At present, the browser's support for WebSocket is already very good, coupled with WeChat Mini Programs's platform support, this communication method, which can greatly improve the client experience, will become more mainstream.
The Server side needs to implement the WebSocket protocol to support WeChat Mini Programs's WebSocket request. In view of the widespread use of SocketIO, scissors stone paper Mini Program, we chose the more famous SocketIO as the server implementation.
Socket IO is relatively simple to use, and it only takes a few lines of code to start the service.
Export class Server {
Init (path: string) {
/ * * Port that server listen on * /
This.port = process.env.PORT
/ * * HTTP Server instance for both express and socket io * /
This.http = http.createServer ()
/ * * Socket io instance * /
This.io = SocketIO (this.http, {path})
/ * * Handle incomming connection * /
This.io.on ("connection", socket = > {
/ / handle connection
})
}
Start () {
This.http.listen (this.port)
Console.log (`- server started. Listen: ${this.port}-`)
}
}
Const server = new Server ()
Server.init ("/ applet/ws/socket.io")
Server.start ()
Copy the code
However, SocketIO and some other server-side implementations have their matching clients to complete the encoding and decoding of the upper layer protocols. However, due to the limitations of Wechat (objects such as window can not be used), the client code of SocketIO can not run on WeChat Mini Programs platform.
After capturing the package of SocketIO communication and studying its client source code, the author encapsulates a WxSocketIO class of about 100 lines suitable for WeChat Mini Programs platform, which can help developers to quickly use SocketIO for WebSocket communication.
Const socket = new WxSocketIO ()
Socket.on ('hi', packet = > console.log (' server say hi:'+ packet.message))
Socket.emit ('hello', {from:' techird'})
Copy the code
If you want to use Wechat's native API, you can also use ws directly on the server side to implement the W3C standard interface. However, SocketIO supports multi-process features, which is very helpful for subsequent horizontal expansion. Tencent Cloud will also plan to launch WebSocket connection services to support large-scale business requirements in the future to reduce business deployment costs.
Communication protocol design
To implement a multi-client interaction service, all message types involved in the middle need to be designed clearly, just like a Mini Program like rock paper scissors, which has the following message types.
Server logic
The logic of the server is simple:
When you receive a user's request to join a room (join), look for a room that is not yet full.
If you find a room, join.
No room found. Create a new room.
Check whether the room joined by the user is full. If it is full, then:
Send a signal to each user in the room to start the game (start)
Start the timer and settle the game at the end of the timer.
Game settlement
In the competition between the two, the winner adds one and the loser minus one, resulting in a basic score x for each player.
For each player, if the score x is greater than 0, it will be regarded as victory, and the number of consecutive victories will be increased by one, otherwise the number of consecutive victories will return to zero.
The score of this Council is the score x times the number of consecutive victories.
Send the results of the game to every player in the room.
Wechat end implementation
WeChat Mini Programs directly uses the above protocol to render for different scenes. The overall state machine is as follows.
After the state machine is sorted out, it is based on the state machine to control when to send the message and how to deal with it after receiving the message.
At this point, I believe that you have a deeper understanding of "Mini Program WebSocket long connection how to use", might as well to practical operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.