Implementing TCP and UDP transport instances in Android _android

Source: Internet
Author: User
Tags readline rfc socket

TCP and UDP are important in network transport and are equally important in Android development.

First let's take a look at what TCP and UDP are.

What is TCP?

Tcp:transmission Control Protocol Transmission Control Protocol TCP is a connection-oriented, reliable, byte-throttling transport layer (Transport Layer) communication protocol, by the IETF RFC 793 description (specified). In the simplified computer network OSI model, it completes the function specified in layer fourth transport layer. The application layer sends a 8-byte data stream to the TCP layer for transmission across the network, and then TCP divides the data stream into a segment of the appropriate length (usually limited by the maximum Transfer Unit (MTU) of the data link layer of the network to which the computer is connected). TCP then passes the result packet to the IP layer, where it transmits packets over the network to the TCP layer of the receiving entity. TCP, in order to ensure that no packet loss occurs, gives each byte an ordinal number, and the serial number also guarantees the sequential reception of packets delivered to the receiving end entity. The receiving entity then sends a corresponding acknowledgment (ACK) to the bytes that have been successfully received, and if the sender entity does not receive a confirmation within a reasonable round-trip time delay (RTT), the corresponding data (if lost) will be sent back. TCP uses a checksum function to verify that the data has errors, and to compute checksums when sending and receiving.

First, after TCP establishes the connection, the communication both sides can transmit the data simultaneously, secondly, he is full-duplex, in the guarantee reliability, uses the timeout retransmission and the incidentally confirmation mechanism.

In the flow control, the sliding window protocol [1] is adopted, which requires retransmission for the unacknowledged grouping within the window.

On the congestion control, the slow start algorithm is adopted.

What is UDP?

UDP is the abbreviation of User Datagram protocol, the Chinese name is the Subscriber packet protocol, is a connectionless transport layer protocol in the OSI Reference Model, and it provides a simple and unreliable information delivery service for transaction-oriented. It is the official specification of the IETF RFC 768 that is UDP. It is used in the network as a TCP protocol for processing packets. In the OSI model, at layer fourth, the transport layer, is at the upper level of the IP protocol. UDP has the disadvantage of not providing datagram grouping, assembling and sorting packets, that is, when a message is sent, it is not possible to know whether it has arrived safely or completely. UDP is used to support network applications that need to transfer data between computers. The UDP protocol is needed for the network applications of many client/server modes including the network video conferencing system. The UDP protocol has been in use for many years since its inception, although its initial brilliance has been overshadowed by similar protocols, but even today, UDP is a very practical and feasible network transport protocol.

As with the well-known TCP (Control Protocol) protocol, the UDP protocol is directly at the top of the IP (Internet Protocol) protocol. According to the OSI (Open Systems Interconnection) Reference model, both UDP and TCP belong to the Transport layer protocol.

The main function of UDP protocol is to compress the network data traffic into the form of datagram. A typical datagram is a transmission unit of binary data. The first 8 bytes of each datagram are used to contain header information, and the remaining bytes are used to contain the specific transmitted data.

The use of TCP and UDP in Android is exactly the same as in Java.

First we look at the TCP connection, and the following figure is a schematic of the TCP connection:

is not very good understanding, here is not much to say, directly to see the code! Practice the truth.

TCP Server-side code:

Copy Code code as follows:

try {
Boolean Endflag = false;
ServerSocket ss = new ServerSocket (12345);
while (!endflag) {
Waiting for client connections
Socket s = ss.accept ();
BufferedReader input = new BufferedReader (Newinputstreamreader (S.getinputstream ()));
Note that the second parameter is true automatically flush, otherwise you need to manually manipulate Output.flush ()
PrintWriter output = Newprintwriter (S.getoutputstream (), true);
String message = Input.readline ();
LOG.D ("Tcp Demo", "Message from Client:" +message);
OUTPUT.PRINTLN ("message received!");
Output.flush ();
if ("ShutDown". Equals (message)) {
Endflag=true;
}
S.close ();
}
Ss.close ();

catch (Unknownhostexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}

TCP Client code:

Copy Code code as follows:

try {
Socket s = new socket ("localhost", 12345);
Outgoing stream Redirect to socket
OutputStream out = S.getoutputstream ();
Note that the second parameter is true automatically flush, otherwise you need to manually manipulate Out.flush ()
PrintWriter output = new PrintWriter (out, true);
Output.println ("Hello ideasandroid!");
BufferedReader input = new BufferedReader (Newinputstreamreader (s)
. getInputStream ());
Read line (s)
String message = Input.readline ();
LOG.D ("Tcp Demo", "Message from Server:" + message);
S.close ();

catch (Unknownhostexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}

Now let's look at UDP:

UDP server-side code:

Copy Code code as follows:

Ports that the UDP server listens on
Integer port = 12345;
The size of the bytes received, the data sent by the client cannot exceed this size
byte[] message = new byte[1024];
try {
Establish a socket connection
Datagramsocket datagramsocket = new Datagramsocket (port);
Datagrampacket datagrampacket = new Datagrampacket (message,
Message.length);
try {
while (true) {
Preparing to receive data
Datagramsocket.receive (Datagrampacket);
LOG.D ("UDP Demo", datagrampacket.getaddress ()
. Gethostaddress (). ToString ()
+ ":" + New String (Datagrampacket.getdata ());
}
catch (IOException e) {
E.printstacktrace ();
}
catch (SocketException e) {
E.printstacktrace ();
}

UDP Client code:

Copy Code code as follows:

public static void Send (String message) {
Message = (Message = = null?) "Hello ideasandroid!": message);
int server_port = 12345;
Datagramsocket s = null;
try {
s = new Datagramsocket ();
catch (SocketException e) {
E.printstacktrace ();
}
InetAddress local = null;
try {
Switch to server-side IP
Local = Inetaddress.getbyname ("localhost");
catch (Unknownhostexception e) {
E.printstacktrace ();
}
int msg_length = Message.length ();
byte[] Messagemessagebyte = Message.getbytes ();
Datagrampacket p = new Datagrampacket (Messagebyte, msg_length, Local,
Server_port);
try {
S.send (P);
catch (IOException e) {
E.printstacktrace ();
}
}

The code needs attention to the place has been commented, I hope this article to help you!

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.