There are many friends in private chat, I said the update is too slow, kill blow blow. Once a week? Isn’t that enough for you?

Okay, I’m not going to write it. ╭ (╯ ^ ╰) ╮!!!!!!

Well, try to keep the delivery released after completing the review. In fact, the previous chapters were written over the weekend and posted on Wednesdays.

In the previous section we discussed network model layering in detail. We know the seven layers and now there are only five. Today we’ll expand on the transport layer PROTOCOLS UDP and TCP. This is because the two protocols are relatively related and short in length. So merge layers in one section.

chapter

  • Android communicating with iot Devices – A concept starter
  • Android communicating with iot devices – The essence of data transfer
  • Android and iot device communication – Network model layering
  • Android and Internet of Things device communication -UDP protocol principle
  • Communication between Android and iot devices -TCP protocol principle
  • Communication between Android and iot devices – based on TCP/IP custom messages
  • Android communicating with iot devices – What is byte order
  • Communication between Android and iot devices – byte packet assembly and parsing
  • Android communicates with iot devices – use UDP broadcast to do device lookup
  • Android and Internet of Things device communication – remote control Android client
  • Android communicates with iot devices -Android makes small servers
  • Android and Internet of Things device communication – debugging tips
  • Android communicates with iot devices – parallel serial and queue
  • Android communicating with iot devices – Data security
  • Android communicates with iot devices – heartbeat
  • Android and Internet of Things device communication – network IO model

directory

  • UDP
  • TCP

User Datagram Protocol (UDP)

It’s a high-speed protocol with unreliable data. Why is it unreliable? Because the TCP counterpart is very reliable and stable. Let’s first look at the UDP packet structure and then explain how the data is transmitted.

UDP packet

As you can see, it’s very simple, there’s nothing special to say, just from the last few videos. The efficiency of UDP is not in packets, but in the transmission mechanism of UDP, which only sends out packets and does not care whether the packets can be received (exist or not).

You must remember when the network is not ping once, this small show of SAO operation of the? It is true that the bottom layer is directly implemented by UDP protocol. The ping process is that the client assembles UDP packets, and the DNS server receives and parses UDP packets and responds to the client. If the ping fails, a timeout occurs, that is, the DNS server does not reply to the client.

So UDP transmission can be understood as data, no matter three seven two one is a go you, bye-bye you le. I don’t check to see if I got it.

In normal cases, a packet is forwarded by routes and switches one layer at a time to the receiving location. They rely on the data link layer and the network layer mentioned in the previous section to find hosts. UDP only cares about ports. The most typical form of UDP is called unicast UDP, in addition to multicast and broadcast. In terms of multicast and broadcasting, we’ll go into more detail and do a little demo in a later section on finding devices.

Transmission Control Protocol (TCP)

TCP is much more stable than UDP. Similarly, we first look at the structure of the newspaper, and then learn the transmission principle.

TCP packet

Let’s focus on a few field descriptions:

  • Serial number: indicates the number of bytes in the entire set of data in which the current packet of the sender resides. Used to ensure the stability of a data set.

  • Ack number: also called an acknowledgement number, indicating the number of bytes received by the receiver and the number of bytes expected for the next set of data.

  • Data offset: Generally not used, but appears in the TCP header if the optional field is added, the offset position must be specified in the data offset, can be expanded from 20 bytes to 60 bytes.

  • Control bits: 6 flag bits URG ACK PSH RST SYN FIN Each flag indicates a control function, that is, an identifier that tells the other party what the current packet is used for.

  • Window: the receiver tells the sender its cache size. Avoid data loss caused by receiving packets that are too large.

Detail of control position

  • URG: Indicates whether the emergency pointer flag is valid.

  • ACK: Verifies whether the serial number is valid.

  • PSH: Refresh the cache flag 1 is valid, 0 is ignored, requiring data to be sent to the application as soon as possible, not stored in the cache. (Java flush method)

  • RST: indicates that the connection is forcibly disconnected when an exception occurs.

  • SYN: indicates the sequence number of connection synchronization.

  • FIN: Finish flag, used to release the connection. 1 Closes the connection.

At first glance you can see that TCP packets are much more complicated than UDP packets, a lot of stuff. Don’t worry, my old boy. Then you don’t have to deal with the bottom line. You just need to know what they’re doing. And it’s worth saying that when you do socket programming in Java, you don’t know the state of the underlying fields at all. At the upper level there is only one input stream and one output stream when processing data. This greatly facilitates the development of the application layer.

TCP Protocol Analysis

We know that TCP is connection-oriented and strictly controls the stability of each transmission. So how does it work? Now let’s actually write some code (Kotlin) and analyze it with wireshark.

The service side

fun main(args: Array<String>) {
  val ss=  ServerSocket(22222);
    while (true) {val accept = ss.accept()
        val dataInputStream = DataInputStream(accept.getInputStream())
        val dataOutputStream = DataOutputStream(accept.getOutputStream())
        val s = dataInputStream.readUTF()
        dataOutputStream.writeUTF("hello Server")
        dataInputStream.close()
        dataOutputStream.close()
        accept.close()
        println(s)
    }
}
Copy the code

The client

fun main(args: Array<String>) {
    val socket = Socket("192.168.0.5".22222);
    val dataOutputStream = DataOutputStream(socket.getOutputStream())
    val dataInputStream = DataInputStream(socket.getInputStream())
    dataOutputStream.writeUTF("hello")
    val s = dataInputStream.readUTF()
    dataInputStream.close()
    dataOutputStream.close()
    socket.close()
    println(s)
}
Copy the code

Note that the Wireshark cannot capture TCP loop packets on the local PC. Otherwise, the Wireshark cannot capture TCP loop packets on the local PC.

  • Run a route add local IP mask 255.255.255.255 route IP metric 1 to the routing table

  • Delete route delete the LOCAL IP address

For the sake of demonstration, I use two network cards here. So the loop IP was added twice to the previous route.

Here, we first open the Server and enter the loop listening state. Then we open the client and send a Hello after connecting, and the Server replies with a Hello Server. Nothing more was done. Let’s take a look at the packages caught using Wireshark.

  • Client:192.168.0.4Port:55705(Operating system protocol stack allocation)
  • Server:192.168.0.5Port:22222(What we defined)

1. After the server is started, the operating system starts to listen for SYN packets on port 22222.

2. The client starts and tries to connect to the server. The operating system protocol stack randomly assigns a sending port.

Handshake:

3. The client assembes a group of SYN packets and sends them to server 22222, marking the CLIENT SEQ as 0. (Completes first handshake)

4. The server receives a SYN packet and assemassemes a GROUP of SYN and ACK packets to tell the client that I have confirmed your SYN packet and expect your next packet to start from 1, marking the server seQ as 0. (Complete second handshake)

5. The client receives a SYN and ACK packet from the server, marks the seQ of the client as 1, and assembles an ACK packet to tell the server that the next ACK packet to be received starts from 1. (Complete the third handshake)

Contract:

6. The client assemps a PSH and ACK package with ACK =1 and sends hello to the server.

7. After receiving the hello packet, the server adds ack to the received packet. Assemble a PSH, ACK and send it to the client with ACK =8.

Wave:

8. After receiving the message from the server, the client updates its seQ =8 and assemps a FIN and ACK package with ACK =15 to disconnect the connection. (The first active wave from the client)

9. The server receives the FIN packet from the client, updates its SEQ value to 15, assemfies a FIN and ACK packet, and sends the packet with ACK value to 8. (Server confirms and starts second wave.)

10. The client receives the ACK packet from the server, checks whether seQ is consistent, assembles a group of ACK packets, and sends the packet to the server. (Third wave)

11. The server receives ack packets from the client, checks whether SEQ is consistent, assembles ACK packets and sends them to the client. (Fourth wave)

The process described above doesn’t make much sense on the face of it, so I hope you can actually open Wireshark and the code and have some fun with it.

Review process:

Handshake: The client and server shake hands three times, telling each other their form size and ACK confirmation number. The over-packet function is realized from ACK and SYN.

Data transfer: When receiving the other party’s data, I put an ACK mark in the next packet to tell the other party how much content I have received and look forward to the starting position of the next set of content.

Wave: confirm whether the packet is complete and then confirm ACK. The real wave is over.

Packet loss or incorrect packet verification: The operating system protocol stack checks the packets with the ACK bit based on the ACK and SEQ numbers. If the packets fail to match the ACK and SEQ numbers, the operating system must resend the packets.


This is the end of the UDP&TCP protocol. The UDP packet fetching process is not demonstrated here, because if TCP knows UDP, it is not a problem. Again, I don’t show you how to use Wireshark, because there are plenty of great tutorials out there.

Even so, I bet readers who are new to TCP/IP will be confused or confused by many concepts and fields sent and sent. Because I’m not good enough for you to read the article and understand it completely. (Quote from Keiko ^ O ^)

Take my advice, don’t give up at this time, while the iron is hot open analysis tools, follow my previous code to run. Then take out a pen and paper to write a picture. Dig deep and really feel their subtleties. You will feel that the design is very good.

Say everybody see really have harvest? If you feel good, and want to reward me once stamp here to reward (I heard that the reward has more effect oh).