A brief introduction to HTTP, TCP, UDP, and Socket
1, the TCP
TCP Overview
TCP is connection-oriented and reliable (data correctness and sequence are guaranteed). It is used to transmit a large amount of data (flow mode). It is slow and requires a lot of overhead (time and system resources) to establish connections.
TCP three-way handshake
To establish a TCP connection, the client and server need to send a total of three packets.
The purpose of the three-way handshake is to connect to the specified port of the server, establish a TCP connection, synchronize the serial number and confirmation number of the connection parties, and exchange TCP window size information. In Socket programming, when the client executes connect(). Three handshakes will trigger.
Let’s start with a few flags: SYN (synchronous), ACK (Acknowledgement) and SEQ (Sequence Number).
First handshake: the client sends a TCP SYN packet at position 1 to indicate the port of the server to which the client intends to connect and the initial Sequence Number X, stored in the Sequence Number field of the packet header.
Second handshake: The server sends back an ACK reply. That is, the SYN flag bit and ACK flag bit are both 1 and the Acknowledgement Number is set to the customer’s serial Number plus 1, that is, X+1.
Third handshake: The client sends an ACK packet again. The SYN bit is 0 and the ACK bit is 1. In addition, the serial number field of ACK sent by the server +1 is sent to the other party in the confirm field. And write the sequence number +1 in the data segment.
TCP waved four times
Removing a TCP connection requires four packets. This is called a four-way handshake.
Why three handshakes to connect and four waves to close?
After receiving a SYN request packet from the Client, the Server sends a SYN+ACK packet. ACK packets are used for reply, and SYN packets are used for synchronization. However, when the Server receives a FIN packet, it may not close the SOCKET immediately. Therefore, the Server can only reply with an ACK packet to tell the Client, “I received the FIN packet you sent.” I can send FIN packets only after all packets on the Server are sent. Therefore, THE FIN packets cannot be sent together. Therefore, a four-step handshake is required.
Advantages and disadvantages of TCP
Advantages:
The reliability and stability of TCP are shown in that TCP establishes a connection with three handshakes before data transfer. During data transfer, TCP provides confirmation, window, retransmission, and congestion control mechanisms. After data transfer, TCP disconnects to save system resources.
Disadvantages:
TCP is slow, inefficient, occupies high system resources, and is vulnerable to attacks. Before transmitting data, TCP establishes a connection, which consumes time. In addition, during data transmission, confirmation mechanisms, retransmission mechanisms, congestion control mechanisms, etc., all consume a lot of time. Each connection consumes hardware resources such as CPU and memory. In addition, TCP has the confirmation mechanism and three-way handshake mechanism, which makes IT easy to be exploited to implement DOS, DDOS, and CC attacks.
2, UDP:
Non – connected, unreliable transmission, used to transmit a small amount of data (packet mode), fast.
UDP does not have the handshake, confirmation, window, retransmission, congestion control mechanisms of TCP. UDP is a stateless transport protocol, so it is very fast when transferring data. Without these mechanisms, UDP is less vulnerable to attack than TCP. However, UDP attacks cannot be avoided, for example, UDP Flood attacks…… The UDP
UDP disadvantages: unreliable, unstable, because UDP does not have the reliable mechanism of TCP, in the data transfer, if the network quality is not good, it is easy to lose packets.
3, the HTTP
(1) HTTP brief introduction
HTTP Protocol, also known as HypertextTransfer Protocol, is the foundation of Web networking and one of the protocols commonly used in mobile networking. HTTP Protocol is an application based on TCP.
(2) the characteristics of HTTP
The most significant feature of HTTP connection is that each request sent by the client needs to be responded by the server. After the request is completed, the server will actively release the connection. The process from establishing a connection to closing a connection is called “one connection”, so HTTP connection is a “short connection”.
- In HTTP 1.0, each request from the client required a separate connection, which was automatically released after the request was processed.
- In HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can overlap without waiting for one request to complete before sending the next.
HTTP is based on client/server (C/S) architectural model
The client sends an HTTP request to the server in the following format: Request line, header, blank line and request data.
The HTTP response also consists of four parts: the status line, the message header, the blank line, and the response body.
(3) Advantages and disadvantages of HTTP
Advantages:
- Application-level interfaces are easy to use
- Programmer development level requirements are not high, fault tolerance is strong
Disadvantages:
- Slow transmission speed and large data packets (Http contains auxiliary application information)
- Real-time interaction, server performance pressure.
- Poor data transmission security
4, the Socket
(1) Brief introduction to sockets
Two programs on the network exchange data through a two-way communication connection, one end of which is called a socket.
At least one pair of sockets is required to establish network communication connections. Socket nature is programming interface (API), TCP/IP encapsulation, TCP/IP also to provide programmers to do network development for the interface, this is socket programming interface; HTTP is a car that provides a concrete form for encapsulating or displaying data; Sockets are engines that provide network communication capabilities.
(2) Advantages and disadvantages of sockets
Advantages:
- Data transmission is byte level, data transmission can be customized, small amount of data (for mobile applications: low cost)
- Short data transmission time and high performance
- It is suitable for real-time information exchange between client and server
- Can be encrypted, strong data security
The Socket faults:
- The transmitted data needs to be parsed and converted into application-level data
- The development level of the developers is high
- Compared with Http protocol transport, increased development
5, TCP HTTP UDP three relations:
- TCP/IP is a protocol suite that can be divided into four layers: the network interface layer, the network layer, the transport layer, and the application layer.
- At the network layer, the protocols include IP, ICMP, ARP, RARP, and BOOTP.
- There are TCP and UDP protocols at the transport layer.
- Protocols at the application layer include FTP, HTTP, TELNET, SMTP, and DNS.
- Therefore, HTTP is itself a protocol, a transport protocol for transferring hypertext from a Web server to a local browser.
HttpURLConnection and HttpClient
Web requests are one of the most common operations in Android development. The Android SDK also provides good support for HTTP(Hypertext Transfer Protocol), which includes two interfaces:
- Standard Java interface (java.NET) -HttpURLConnection, can achieve simple url-based request, response function;
- Apache interface (org.appache. HTTP) — HttpClient, which is much more powerful to use.
However, in the SDK of android API23, Google removed HttpClient. Google recommends using httpURLconnection for network access.
HttpURLconnection is HTTP based and supports various request modes, such as GET, POST, PUT, and DELETE. The most common ones are GET and POST. The following sections describe these two request modes.
1, HttpURLConnection
A class to access the basic functionality of the HTTP protocol is already provided in the JAVa.net package of the JDK: HttpURLConnection.
HttpURLConnection is a standard Java class that inherits from URLConnection and can be used to send GET or POST requests to specified websites.
2, httpclient
HttpClient is a subproject of Apache Jakarta Common that provides an efficient, up-to-date, feature-rich client programming toolkit that supports the latest versions and recommendations of the HTTP protocol.
Three: Common Android network framework
1, the Android – async HTTP
A brief introduction to Android-async-HTTP
Android-async-http is a powerful network request library based on the Apache HttpClient library of asynchronous network request processing library, network processing is based on Android non-UI threads, through the callback method to process the result of the request. Unfortunately for the Android 6.0 (API 23) SDK, org.apache.http.* is no longer available (only a few classes remain).
Android – async HTTP advantages
Advantages:
- Process the result of the request in an anonymous callback
- Make HTTP requests outside of the UI thread
- File breakpoint upload
- Intelligent retry
- Gzip compression by default
- Supports parsing to Json format
- Cookies can be persisted to Share preference
2, afinal
Afinal brief introduction
Afinal is an open source Android ORM and IOC application development framework, which is characterized by small and flexible, less code intrusion. In Android application development, through afinal ioc framework, such as UI binding, event binding, through annotations can be automatically bound. Through afinal ORM framework, without any configuration information, a line of code can add, delete, change and check the Android SQLite database. At the same time, Afinal embedded finalHttp and other easy-to-use tools, you can easily operate HTTP requests.
Afinal main components
- FinalHttp: used to request HTTP data, direct Ajax request, file upload, resumable download file, etc
- FinalBitmap: Used to display bitmap images, regardless of thread concurrency and OOM.
- FinalActivity: You can annotate controls and events without writing code.
- FinalDb: Android SQLite ORM framework, a line of code to do add, delete, change, check.
Afinal characteristics
- The design is simple and compact and flexible
- Orm has zero configuration, but can be configured, and can be more powerful through flexible annotation configuration
- Database query support DbModel, you can easily carry out a variety of complex queries
- Android’s UI and event bindings are entirely annotated without a line of code
- HTTP requests support Ajax requests
- Small size (less than 100KB) and does not rely on third-party JAR packages
Advantages and disadvantages afinal
Advantages of Android ORM framework, a line of code can be added, deleted, changed and checked. Support one-to-many, many-to-one query.
Disadvantages currently do not support the compound primary key, and the SUPPORT for SQL statements is also very limited, some more complex business logic implementation is very troublesome!
3, xUtils
XUtils brief introduction
XUtils is an Android open source framework developed on the basis of Afinal. XUtils 3.0 has been released recently, which improves the performance of the framework while adding new functions.
Here is the official (github.com/wyouflf/xUt…) XUtils3 introduction:
- XUtils includes many useful Android tools;
- XUtils supports large file uploads (more than 2G), more comprehensive HTTP request protocol support (11 predicates), a more flexible ORM, more event annotation support, and is not obtuse.
- XUitls is minimum compatible with Android 2.2 (API Level 8)!
- XUtils3 change more so established a new project is not in the old version (github.com/wyouflf/xUtils) continue to maintain, compared with the old version:
- HTTP implementation replaces HttpClient with UrlConnection, automatically resolves callback generics, more secure breakpoint continuation strategy;
- Support standard Cookie policy, distinguish domain, path;
- Event annotations improve performance by removing uncommon features;
- Database API simplification to improve performance, achieve the same performance as greenDao;
- Image binding support GIF (affected by system compatibility, some GIF files can only be static display), webp; Support rounded corner, circle, square cutting, support automatic rotation.
XUtils main components
Currently xUtils mainly has four modules: ViewUtils module:
- The IOC (Control Inversion) framework in Android, fully annotated for UI, resource and event binding;
- The new event binding method, using the obfuscation tool obfuscation can still work properly;
- Currently used 20 kinds of support event, see ViewCommonEventListener classes and packages. Com lidroid. Xutils. The annotation. The event.
HttpUtils module:
- Support synchronous and asynchronous requests;
- Support large file upload, upload large files will not oom;
- Support GET, POST, PUT, MOVE, COPY, DELETE, HEAD, OPTIONS, TRACE, CONNECT requests;
- Download support for 301/302 redirection and support for setting whether to rename downloaded files according to Content-Disposition;
- Requests that return text content (only GET requests are enabled by default) support caching and you can set the default expiration time and expiration time for the current request.
BitmapUtils module:
- When loading bitmap, there is no need to consider oom and image dislocation in the process of loading Bitmap and Android container rapid sliding.
- Support to load network pictures and local pictures;
- Memory management using LRU algorithm, better manage bitmap memory;
- Configurable thread loading thread number, cache size, cache path, loading display animation, etc…
DbUtils module:
- Android in the ORM (object relational mapping) framework, a line of code can be added, deleted, changed and checked;
- Support transactions, off by default;
- Table names, column names, foreign keys, uniqueness constraints, NOT NULL constraints, CHECK constraints, etc. (please annotate table names and column names if you need to confuse).
- Supports binding foreign keys. When saving entities, entities associated with foreign keys are automatically saved or updated.
- Automatic loading of foreign key associated entities, supporting delayed loading;
- Support chain expression query, more intuitive query semantics
4. Volley Framework
Volley’s brief introduction
Volley, a new network communication framework, was introduced at Google I/O 2013. Volley can access the network data, also can load images, and a substantial adjustment in terms of performance, the design target is very suitable for to data volume is not large, but frequent communication network operation, for the large amount of data in the network operation, such as the download file, etc., Volley performance will be very bad. Before using Volley, please download Volley library and put it in liBS directory and add it to the project.
The main characteristics of Volley
- Good scalability. Volley is mostly based on interface design, configurable.
- A certain degree of compliance with the Http specification, including return ResponseCode(2xx, 3xx, 4xx, 5xx) processing, request header processing, caching mechanism support, etc. Retry and priority definition are supported.
- By default, Android2.3 and above are based on HttpURLConnection, while the following are based on HttpClient. The differences and advantages of these two are described in 4.2.1 Volley.
- Provides a simple image loading tool.
Features provided by Volley
- Asynchronous download of JSON, images, etc.
- Scheduling of network requests
- Priority processing of network requests
- The cache
- Multilevel cancel request
- Interworking with activities and life cycles (cancelling all network requests at the end of an Activity)
Advantages and disadvantages Volley
advantages
- Ideal for small data volume, but frequent communication network operations
- You can call the server directly from the main thread and process the return result
- Request cancelling, easy to extend, interface oriented programming
- The network request thread NetworkDispatcher is enabled by default for 4, which can be optimized through the phone CPU number
- Keep disk and memory responses consistent by using standard HTTP caching mechanisms
- Communication is faster, more stable and simpler
disadvantages
- I’m using the HttpURLConnection class from HttpClient
- 6.0 does not support the HttpClient, if you want to support to add org. Apache. HTTP. Legacy. The jar
- Volley is terrible for large file downloads
- Only HTTP requests are supported
- Image loading performance is mediocre
- It is not suitable for uploading and downloading big data
- Not being able to download files: this is where it kills
Why Volley is used:
- Efficient Get/Post data request interaction
- Loading and caching of network images
- Google official launch
- Stable and robust performance
5, okhttp
Okhttp profile
An open source project for handling web requests, android’s hottest lightweight framework, contributed by Square (which also contributed Picasso), HttpClient is used to replace HttpUrlConnection and Apache HttpClient.
Okhttp advantage
- Support for HTTP2/SPDY (SPDY is a TCP based transport layer protocol developed by Google to minimize network latency, improve network speed, and optimize the user experience on the network) Can merge multiple requests to the same host
- Allows all requests connected to the same host address to improve request efficiency
- The socket automatically selects the best route and supports automatic reconnection. The socket connection pool is automatically maintained, which reduces the number of handshakes, reduces the request delay, and reduces the number of requests to the server by sharing sockets
- The Headers based caching strategy reduces repeated network requests.
- Cache response data to reduce repeated network requests
- Reduces data traffic consumption
- Automatically handles GZip compression
- OkHttp uses Okio to greatly simplify data access and storage. Okio is a library that enhances java.io and java.nio.
- OkHttp also handles proxy server issues and SSL handshake failures.
The flow chart of okhttp
\
Okhttp function
- PUT, DELETE, POST, and GET requests
- Http-based file upload
- Upload and download files
- Upload and download progress callback
- Load images (internal image size automatically compressed)
- Support request callback, directly return object, object collection
- Session persistence is supported
- Support self-signed website HTTPS access, provide method Settings under the certificate on the line
- Support to cancel a request
6, Retrofit
Introduction of Retrofit
Both Retrofit and OkHTTP came from Square, and Retrofit is a wrapper around OkHTTP. Leaving the web requests to Okhttp, retrofit is a simple configuration tool for web requests, written by Android guru JakeWharton.
Retrofit features
- By encapsulating rest apis as Java interfaces, we can encapsulate the interfaces according to business requirements. Actual development may encapsulate several different Java interfaces to meet business requirements. (Note: Retrofit annotations are used here: get,post)
- We use Retrofit to encapsulate our implementation classes that generate our interfaces, which is really cool. Instead of implementing it ourselves, Retrofit automatically generates it all for us through annotations.
- Call the interface method that implements our class object.
Why Retrofit
-
When dealing with HTTP requests, it is difficult to deal with different scenarios or boundary cases. Retrofit takes the headaches out of thinking about network state, retrying after a failed request, and dealing with HTTPS.
-
Of course you can also choose Android-Async-HTTP and Volley, but why Retrofit? First, it’s efficient, second, Retrofit is powerful and flexible in configuration, and second, it works seamlessly with OkHttp.
-
Before Retrofit2, OkHttp was an optional client. In Retrofit2, Retrofit is strongly coupled with OkHttp to make better use of OkHttp, including using OkHttp to solve some tricky problems.
The flow chart of Retrofit
\
Retrofit the pros and cons
Advantages:
- You can configure different HTTP clients to implement network requests, such as OKHTTP and HttpClient
- The requested method parameter annotations can be customized
- Supports synchronous, asynchronous, and RxJava
- Super decoupled
- Different deserialization tools can be configured to parse the data, such as JSON, XML, and so on
- It is very convenient and flexible to use
- The framework uses a number of design patterns (read the source code for those interested)
Disadvantages:
- You cannot touch serialized entity and response data
- The enforcement mechanism is too strict
- Using a converter is inefficient
- Only simple custom parameter types are supported