Comparative Analysis of the Differences between TCP and UDP In this article, the differences between the two are analyzed in terms of reliability, data transmission, applicable scenarios, etc. The purpose of this article is to introduce how to connect one phone to another phone via a hotspot on an Android device. In this scenario, what aspects should be considered in the complete UDP communication module, how should it be optimized, and how to avoid some pitfalls?
Using UDP in Java We all know that most Android applications are developed using Java. How do you use the UDP protocol in Java? We didn't talk about Socket in the previous article. In fact, Socket can be understood as the encapsulation of TCP and UDP protocols at the program usage level, providing some APIs for programmers to call and develop. This is the most superficial meaning of Socket. In Java, the classes related to UDP include DatagramSocket, DatagramPacket, etc. Their usage will not be introduced in detail here. OK, assuming that everyone has a general understanding of their use, we can officially start the content of this article. Initialize a UDPSocket First create a class called UDPSocket.
In the construction method, we perform some initialization operations. Simply put, we create a thread pool and record the current time in milliseconds. As for what they are used for, see below:
Here we first create a DatagramSocket as a "client". In fact, UDP itself does not have the concept of client and server, but only the concept of sender and receiver. Let's temporarily regard the sender as a client. When creating a DatagramSocket object, a port number is passed in. This port number can be defined within a range, indicating that this DatagramSocket listens for data on this port. Then a DatagramPacket object is created as the receiving packet of the data. ***Call startSocketThread to start the thread that sends and receives data.
First, the purpose of the clientThread thread is to call the DatagramSocket receive method. Since the receive method is blocked, it cannot be placed in the main thread, so a child thread is naturally started. receiveMessage is used to process the received UDP datagram. We will not look at this method for receiving data first, after all, no one has sent a message yet, so there is naturally no question of receiving it. Heartbeat packets maintain a "long connection" Coming to the first point of this article, we all know that UDP itself has no concept of connection. The scenario of applying UDP and TCP on the Android side is that one mobile phone connects to the hotspot of another mobile phone, and the two are in the same local area network. When the two do not know the existence of each other, how can they find each other? Through the heartbeat packet method, both parties send a UDP packet at regular intervals. If the other party receives it, they can know the other party's IP and establish communication.
The purpose of this heartbeat is to send a message via sendMessage every ten seconds to see if the other party can receive it. If the other party receives the message, the lastReceiveTime time is refreshed. Here I send a string to the other party every ten seconds.
Here is the code to send a message. When I first filled in the parameters of DatagramPacket, I had a question. The targetAddress is actually my own IP address. The question is, if I fill in my own IP address and the other party's port, how can I find the other party? You may wonder where the "192.168.43.255" IP address comes from and why it is defined like this? First, turn on the hotspot on your Android phone, which can be understood as a gateway with a default IP address: "192.168.43.1" This IP address is not made up by me. It is defined in the Android source code as follows: WifiStateMachine
So I know the IP address of the party that opens the hotspot, and UDP has another feature when sending messages, that is, the messages sent out can be received by all devices in the entire gateway, so my own IP address is set to "192.168.43.255", so this IP address and "192.168.43.1" are in the same gateway, and the messages you send can be received by it. As for how to determine whether two IP addresses are in the same network segment: Determine the size of two IPs and whether they are in the same network segment Let’s make a stage summary: First, we created a sending DatagramSocket and started a heartbeat program to send a heartbeat packet at a certain interval. Because I know that the IP address of the hotspot is the default "192.168.43.1", and the characteristic of UDP is that all devices in the same network segment can receive the sent message. So the sender's IP address is set to "192.168.43.255" in the same network segment as the hotspot. Events and data The two modules, event and data, are closely related to the business. Let's talk about data first. The data format sent by both parties can be defined at will. Of course, I think it is better to define it in the conventional Json format. It can include some key event fields: such as broadcast heartbeat packets, response packets to the other party when receiving heartbeat packets, timeout offline packets, and various business-related data, etc. Of course, the data is converted into a binary array when it is sent. There is no problem sending Chinese characters, pictures, etc., but there may be some details that need attention. Just google it at any time. Let's talk about the incident: What are the non-business related events? for example:
How are events sent out and notified to each page? You can use Listener or other third-party libraries of event bus, it’s up to you to choose. Processing received messages
There are several points worth noting when processing received messages:
The concept of "user" We have discussed the characteristics of UDP above. If a mobile phone has turned on the hotspot and multiple mobile phones are connected to it, it can receive messages sent by multiple mobile phones. If the sender's port is the same as the receiver's port, even the message you sent yourself can be received by yourself. This is very embarrassing, that is, we have to exclude messages sent to ourselves and distinguish messages sent from different mobile phones. At this time, there should be a concept of "user". Create a User object and check which attributes you can use to view your business. The examples in this article include ip, imei, and softversion.
I won't expand all the codes here. If you have the IMEI number of the mobile phone, it is easy to distinguish the identity. You can distinguish different senders and remove the messages sent to yourself. Of course, if more information is needed, you can distinguish it according to your own business and send it as a messge through Socket. Written at the end: Up to now, most of the contents of this article have been introduced. Some students may ask, you need to use a heartbeat to maintain a fake "long connection", which is troublesome to use, and you may also suffer from the pain of packet loss caused by UDP, why not choose TCP? Good question, in fact, this version was the first version made at that time, and then the TCP+UDP method was used to complete this module. Let's take a look at the improved version with TCP in the next article. |
<<: Tips for using Erdua, a mobile web debugging tool
>>: Introduce Gradle dependencies in Android projects like npm
Electric car time-sharing rental (also known as &...
Today I’d like to share with you an analysis of h...
When novice webmasters carry out website optimiza...
Recently, advertisements for a social APP have be...
When I saw a netizen asking "Are there bacte...
In the afternoon, one WeChat message and one phon...
On November 12, BYD and Huawei jointly launched t...
Preface If there is any company in China's cu...
In 1988, about 10 kilometers off the coast of Sar...
According to reports, at the recently held Second...
How much does it cost to be an agent of Guang'...
Operation and promotion require the most user res...
Most planners have heard of theories such as USP,...
The Large Hadron Collider (LHC) in Geneva is the ...
[[421353]] Following the QQ version upgrade, WeCh...