Android Development: How to implement TCP and UDP transport

Source: Internet
Author: User
Tags rfc

TCP and UDP are important in network transmission, as well as in Android development.

First look at what TCP and UDP are.

What is TCP?

Tcp:transmission Control Protocol Protocol TCP is a connection-oriented, reliable, byte-stream-based transport layer (Transport layer) communication protocol, which is provided by the IETF RFC 793 description (specified). In the simplified computer network OSI model, it accomplishes the functions specified by the fourth layer of the transport layer. The application layer sends a 8-byte data stream for inter-network transmission to the TCP layer, and then TCP splits the data stream into a segment of the appropriate length (the limit of the maximum Transmission Unit (MTU) of the data link layer of the network that is usually connected to the computer). TCP then passes the result packet to the IP layer, which transmits the packet over the network to the TCP layer of the receiving side entity. TCP in order to ensure that no packet loss occurs, give each byte a sequence number, while the serial number also guarantees the delivery to the receiving entity of the packet received sequentially. The receiving entity then sends a corresponding acknowledgment (ACK) to the successfully received byte, and if the sending entity does not receive a confirmation within a reasonable round trip delay (RTT), then the corresponding data (assuming it is lost) will be re-transmitted. TCP uses a checksum function to verify the data for errors, and to calculate checksums when sending and receiving.

First, after the TCP establishes the connection, both sides of the communication can carry on the data transmission simultaneously, secondly, he is full duplex, in the guarantee reliability, uses the time-out retransmission and the piggyback confirmation mechanism.

In the flow control, using the Sliding window Protocol [1], the Protocol stipulates that the window within the unacknowledged group needs to be re-transmitted.

In 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 provides a simple and unreliable information transfer service for transaction. It is the official specification of the IETF RFC 768 that is UDP. It is used in the network as the TCP protocol to process packets. In the OSI model, the fourth layer, the transport layer, is in the upper layer of the IP protocol. UDP has the disadvantage of not providing datagram grouping, assembling, and not sorting packets, that is, when the message is sent, it is not possible to know whether or not it arrives safely and completely. UDP is used to support network applications that need to transfer data between computers. A large number of client/server mode network applications, including the network video conferencing system, require the use of UDP protocol. UDP protocol has been used for many years since its inception, although its original glory has been obscured by some similar agreements, but even today, UDP is still a very practical and feasible network Transport layer protocol.

As with the well-known TCP (Transmission Control Protocol) Protocol, the UDP protocol is located directly on the top level of the IP (Internet Protocol) protocol. Depending on the OSI (Open Systems Interconnect) Reference Model, both UDP and TCP are transport-layer protocols.

The main function of the UDP protocol is to compress the network data traffic into the form of the datagram. A typical datagram is a transmission unit of binary data. The first 8 bytes of each datagram are used to contain the 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, one for the TCP connection:

There is not much to say, look directly at the code!

TCP Server-side code:

[Java]View Plaincopy
  1. try {
  2. Boolean Endflag = false;
  3. ServerSocket ss = New ServerSocket (12345);
  4. While (!endflag) {
  5. //Waiting for client to connect
  6. Socket s = ss.accept ();
  7. BufferedReader input = new BufferedReader (Newinputstreamreader (S.getinputstream ()));
  8. //Note the second parameter data is true will automatically flush, otherwise need to manually operate Output.flush ()
  9. PrintWriter output = Newprintwriter (S.getoutputstream (),true);
  10. String message = Input.readline ();
  11. LOG.D ("TCP Demo", "message from Client:" +message);
  12. OUTPUT.PRINTLN ("message received!");
  13. //output.flush ();
  14. if ("ShutDown". Equals (Message)) {
  15. Endflag=true;
  16. }
  17. S.close ();
  18. }
  19. Ss.close ();
  20. } catch (Unknownhostexception e) {
  21. E.printstacktrace ();
  22. } catch (IOException e) {
  23. E.printstacktrace ();
  24. }
  25. TCP Client code:
  26. ?
  27. try {
  28. Socket s = new socket ("localhost", 12345);
  29. //Outgoing stream redirect to socket
  30. OutputStream out = S.getoutputstream ();
  31. //Note the second parameter data is true will automatically flush, otherwise need to manually operate Out.flush ()
  32. PrintWriter output = new PrintWriter (out, true);
  33. Output.println ("Hello ideasandroid!");
  34. BufferedReader input = new BufferedReader (Newinputstreamreader (S
  35. . getInputStream ()));
  36. //Read line (s)
  37. String message = Input.readline ();
  38. LOG.D ("TCP Demo", "message from Server:" + message);
  39. S.close ();
  40. } catch (Unknownhostexception e) {
  41. E.printstacktrace ();
  42. } catch (IOException e) {
  43. E.printstacktrace ();
  44. }

Below we look at UDP:

UDP server-side code:

[Java]View Plaincopy
  1. Ports that the UDP server listens on
  2. Integer port = 12345;
  3. //Received byte size, the data sent by the client cannot exceed this size
  4. byte[] message = new byte[1024];
  5. try {
  6. //Establish socket connection
  7. Datagramsocket datagramsocket = new Datagramsocket (port);
  8. Datagrampacket datagrampacket = new Datagrampacket (Message,
  9. Message.length);
  10. try {
  11. While (true) {
  12. //Prepare to receive data
  13. Datagramsocket.receive (Datagrampacket);
  14. LOG.D ("UDP Demo", datagrampacket.getaddress ()
  15. . Gethostaddress (). ToString ()
  16. + ":" + new String (Datagrampacket.getdata ()));
  17. }
  18. } catch (IOException e) {
  19. E.printstacktrace ();
  20. }
  21. } catch (SocketException e) {
  22. E.printstacktrace ();
  23. }


UDP Client code:

[Java]View Plaincopy
    1. Public static void Send (String message) {
    2. Message = (Message = = null?)    "Hello ideasandroid!": message);
    3. int server_port = 12345;
    4. Datagramsocket s = null;
    5. try {
    6. s = new Datagramsocket ();
    7. } catch (SocketException e) {
    8. E.printstacktrace ();
    9. }
    10. InetAddress local = null;
    11. try {
    12. //Swap server-side IP
    13. Local = inetaddress.getbyname ("localhost");
    14. } catch (Unknownhostexception e) {
    15. E.printstacktrace ();
    16. }
    17. int msg_length = Message.length ();
    18. byte[] Messagemessagebyte = Message.getbytes ();
    19. Datagrampacket p = new Datagrampacket (Messagebyte, Msg_length, Local,
    20. Server_port);
    21. try {
    22. S.send (P);
    23. } catch (IOException e) {
    24. E.printstacktrace ();
    25. }
    26. }

Android Development: How to implement TCP and UDP transport

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.