Android basics tutorial -- 7.6.1 Socket Learning Network basics, android7.6.1

Source: Internet
Author: User

Android basics tutorial -- 7.6.1 Socket Learning Network basics, android7.6.1
Basic Android tutorial -- 7.6.1 Socket Learning Network Basics

Tags (separated by spaces): basic Android tutorial

This section introduces:

In order to take care of beginners who have never learned Java Socket, or the concepts related to network protocols involved in development of Java 1 for Android,
After all, during the interview, the interviewer asked me how many layers of network protocols are there? Which layer is the IP protocol? What is Socket?
What are the differences? What layer is the TCP and UDP protocols? What's the difference... Well, this... Therefore, the conceptual theory of this section is still very good.
Necessary! So let's not talk much about it. Start this section ~

1. Analysis of OSI Layer-7 Network Model

Of course, we are not specialized in network engineering. As long as we know what layers are there, we can probably do it!

OSI Layer-7 network model (from bottom up):

  • Physical Layer (Physical): Data communication between devices provides transmission media and interconnection devices to provide reliable data transmission
    Environment. It can be understood as the physical media part transmitted over the network, suchNic, network cable, Hub, repeater, ModemEtc!
    At this layer, the data has not yet been organized and is only processed as the original bit stream or electrical voltage. The unit of this layer is:Bit
  • Data link layer (Datalink): It can be understood as a data tunnel. Its main function is to perform operations on unreliable physical lines.
    Reliable data transmission. The function of the change layer includes physical address addressing, data frame formation, traffic control, data error detection, and re-transmission!
    In additionData Link refers: The physical layer must provide transmission media and connections for data communication between devices. Media is
    For a long time, the connection has a lifetime. During the connection lifetime, data communication between the two ends can be performed once or multiple times.
    Every communication requires two steps: establishing a communication contact and removing a communication contact! This establishedData transmission relationship~
    Devices on this layer include:Nic, bridge, and network switchIn addition, the unit of this layer is:Frame
  • Network): The main function is to translate the network address into the corresponding physical address, and decide how to send data from
    The sender routes the data to the receiver. The so-called routing and path retrieval: A terminal may need to communicate with multiple terminals.
    Link any two terminal device data! To put it simply, establish a network connection and provide services for the upper layer!
    Devices on this layer include:Routing! The unit of this layer is:Data PacketsIn addition, the IP protocol is at this layer!
  • Transport): Provides communication services to the upper-layer application layer, which is oriented to the highest level of the communication part.
    The lowest layer in user functions. Receives Session Layer data, splits the data when necessary, and delivers the data to the network
    And ensure that these data segments arrive at the peer end effectively! Therefore, the unit of this layer is:Data SegmentAnd this layer has two very important
    The Protocol is:TCP transmission control protocolAndUDP User Datagram ProtocolThis is also the core part of this chapter!
  • Session Layer): Establishes, maintains, and terminates communications between two nodes in the network. Establish a communication link,
    Keep the communication links in the session process open, synchronize the conversations between the two nodes, and determine whether the communication is interrupted or not.
    Determines where to resend, that is, the establishment and management of sessions between users on different machines!
  • Presentation layer (Presentation): Explain the commands and data from the application layer, and grant corresponding syntaxes
    To the Session Layer in a certain format. Its main function is to "handle user information representation problems, such as encoding,
    Data format conversion, encryption, decryption, compression, and decompression
  • Application): The highest level of the OSI reference model to provide network services for your applications.
    On the basis of other layer-6 work, it is responsible for completing the connection between applications in the network and the network operating system, and establishing the connection with end users, complete various protocols, such as supervision, management, and service, required for various network services and applications proposed by network users. In addition, this layer is responsible for coordinating the work between applications. Services and protocols provided by the application layer include: file service, directory service, file transmission service (FTP), remote login service (Telnet), and email service (e-mail) print Service, Security Service, Network Management Service, database service, etc.

Okay. We have briefly described the OSI Layer-7 network model. The following is a summary:

OSI is an ideal model. Generally, a network system only involves several layers. In a layer-7 model, each layer provides a special
From the perspective of network functions:

  • The following four layers (physical layer, data link layer, network layer, and transmission layer) mainly provide data transmission and exchange functions,
    That is, communication between nodes is dominant.
  • As a bridge between the upper and lower layers, Layer 3 is the most critical part of the network architecture;
  • The upper three layers (Session Layer, presentation layer, and application layer) Provide information and data processing between users and applications.

In short, the next four layers mainly implement the Communication Subnet function, and the last three layers mainly implement the resource subnet function.

-- For the above content, refer to: OSI Layer-7 Model

2. layer-4 TCP/IP Model

TCP/IP is synonymous with a group of Protocols. It also includes many protocols and forms a TCP/IP protocol cluster.
The TCP/IP protocol cluster is divided into four layers. The IP address is located at the second layer of the protocol cluster (corresponding to the third layer of OSI), and the TCP is located at the third layer of the protocol cluster.
(Corresponding to the fourth layer of OSI ). The TCP/IP communication protocol adopts a layer-4 structure, and each layer calls the layer provided by the next layer.
Network to meet your needs. The four layers are:

  • Application Layer: Application communication layer, such as simple Email transmission (SMTP), file transfer protocol (FTP ),
    Remote Network Access Protocol (Telnet.
  • Transport Layer: In this layer, it provides data transmission services between nodes, such as transmission control protocol (TCP ),
    User Datagram Protocol (UDP). TCP and UDP add data to the data packet and transmit it to the next layer,
    This layer transmits data and determines that the data has been delivered and received.
  • Network Interconnection layer: Provides basic data packet transmission functions so that each data packet can reach the destination.
    For example, Internet Protocol (IP ).
  • Host to Network Layer: Manages the actual network media and defines how to use the actual network.
    (Such as Ethernet and Serial Line) to transmit data.
3. TCP/UDP differences

Okay, let's talk about the first two points. I just want to popularize the OSI Layer-7 model and the TCP/IP layer-4 model. What we will talk about next is
Some concepts related to our Socket development!

1) IP Address

2) Port

1.Used to differentiate different applications
2.The port number ranges from 0 to 65535, and 0 to are not reserved by the system. Do not use these ports as much as possible!
3.The IP address and port number constitute our Socket, which is the end point of the two-way communication link between network running programs,
Is the basis of TCP and UDP!
4.Port used by common protocols: HTTP: 80, FTP: 21, TELNET: 23

3) Comparison Between TCP and UDP:

TCP process details:

First, TCP/IP is a protocol cluster, which includes many protocols. UDP is only one of them. Named TCP/IP protocol,
Because of TCP, IP protocol is two very important protocols.
Next we will explain the differences between the TCP protocol and the UDP protocol:
TCP(Transmission Control Protocol) is a connection-oriented Protocol, that is, sending and receiving data money.
, All need to establish a reliable link with the opposite side, which is also the TCPThree-way handshakeAnd TCPFour Waves!
Three-way handshake:
When establishing a TCP connection, the client and the server need to send a total of three packets to confirm the establishment of the connection,
In Socket programming, the client executes connect to trigger this process. The specific flowchart is as follows:

  • First handshake: The Client sets the flag SYN to 1, generates a random value seq = J, and sends the packet to the Server,
    The Client enters the SYN_SENT status and waits for confirmation from the Server.
  • Second handshake: After the Server receives the data packet, the flag SYN = 1 knows the Client request to establish a connection. The Server will
    Both SYN and ACK are set to 1, ack = J + 1, a random value seq = K is generated, and the packet is sent to the Client to confirm the connection request.
    The Server enters the SYN_RCVD status.
  • Third handshake: After receiving the confirmation, the Client checks whether ack is J + 1 and ACK is 1. If yes, the flag is ACK.
    Set to 1, ack = K + 1, and send the packet to the Server. The Server checks whether ack is K + 1 and ACK is 1. If yes
    After the connection is ESTABLISHED successfully, the Client and Server enter the ESTABLISHED State and complete three handshakes. Then, the Client and Server can
    Data transmission started.

Four Waves:
To terminate a TCP connection, the client and the server need to send a total of four packets to confirm the disconnection.
In Socket programming, this process is triggered by the close of the client or the server side. The specific flowchart is as follows:

  • The first wave: The Client sends a FIN to disable data transmission from the Client to the Server. The Client enters
    FIN_WAIT_1 status
  • Second Wave: After the Server receives the FIN, it sends an ACK to the Client and confirms that the serial number is the received serial number + 1 (same as SYN,
    A fin occupies a serial number), and the Server enters the CLOSE_WAIT status.
  • Third Wave: The Server sends a FIN to disable data transmission from the Server to the Client. The Server enters the LAST_ACK
    Status.
  • Fourth Wave: After the Client receives the FIN, the Client enters the TIME_WAIT status, and then sends an ACK to the Server, confirming that the serial number is received by the serial number + 1. The Server enters the CLOSED status and completes four waves.
    In addition, it may be because a colleague initiates an active shutdown:

Another common problem may be: Why is a three-way handshake while a four-way handshake is used to close the connection?
A: The server is in the LISTEN status. After receiving the SYN packet for the connection request, the server puts ACK and SYN in one packet.
Send to the client. When the connection is closed, when receiving the FIN message from the other party, it only indicates that the other party no longer sends data but returns
If you can receive data, you may not send all the data to the other party. Therefore, you can close the data immediately or send some
After the data is sent to the other party, send a FIN message to the other party to agree to close the connection now. Therefore, both ACK and FIN
Separate sending.

UDP protocol details:

UDP(User datav Protocol) User Datagram Protocol, non-connection Protocol, the source end and the terminal do not
Establish a connection. when it wants to transfer data, it simply captures data from the application and throws it to the network as quickly as possible.
At the sender end, the speed at which UDP transmits data is only dependent on the speed at which the application generates data, the ability of the computer, and the transmission bandwidth.
At the receiving end, UDP puts each message segment in the queue, and the application reads one message segment from the queue each time.
Compared with TCP, no link is required. The structure is simple, and the correctness cannot be guaranteed. packet loss is easy.

-- The preceding content is taken from:
TCP/IP three-way handshake and four-way handshake
Difference Between TCP and UDP)

4. Several key network classes in Java:

Java provides four network functions for different network communication layers:

  • InetAddress:
    Used to Identify hardware resources on the network
  • URL:
    Unified resource positioning operator. You can directly read or write data on the network through URLs.
  • Socket and ServerSocket:
    Socket-related classes for network communication using the TCP protocol
  • Datax:
    Use UDP protocol to save data in the datagram and communicate through the network

In this section, we will only introduce the first two classes. The Socket and datasync to TCP and UDP sections will be explained again!

~ Example of InetAddress:

Sample Code:

Public class InetAddressTest {public static void main (String [] args) throws Exception {// gets the instance of the local InetAddress: InetAddress address = InetAddress. getLocalHost (); System. out. println ("local name:" + address. getHostName (); System. out. println ("IP address:" + address. getHostAddress (); byte [] bytes = address. getAddress (); System. out. println ("IP address in byte array format:" + Arrays. toString (bytes); System. out. println ("directly output InetAddress object:" + address );}}

Running result Diagram:

~ URL: I don't need to talk about this. I forgot to refer to the previous Http protocol ~

Summary:

This section is full of concepts. It may seem awkward, but it doesn't matter if you don't understand it. You know that layer-7 models are called
What are you doing? There are three TCP handshakes and four waves! Of course, this is just
Interview handling ~ In actual development, how can we solve this problem... Direct Socket, right ~ Well, next we will start learning.
Socket Communication in Android ~ Thank you ~

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.