Java TCP/UDP socket programming process summary, udpsocket

Source: Internet
Author: User

Java TCP/UDP socket programming process summary, udpsocket

Recently I learned a little bit about java socket programming. Although the overall process is not very complicated, it is worth summing up.

Socket

A Socket is an abstraction for the network. An application can read and write data on the network. Just like using a file handler to write data to a storage device. Depending on the TCP protocol and UDP protocol, there are two different Sockets for the two protocols in terms of network programming. One is for byte streams and the other is for packets.

It is easier to understand the composition of the socket itself. Since the application communicates through socket, there must be a server and a client. Therefore, it must contain a corresponding IP address. In addition, the server must provide a series of services on this address, so a series of corresponding windows are required to provide services. So there is a corresponding Port ). The port number is a 16-bit binary number, and the range is from (0-65535 ). The IP address and port number constitute the socket. The following figure shows the relationship between the socket and the entire TCP/IP:

 

TCP

TCP is mainly a connection-oriented protocol. It includes functions such as establishing and removing connections and ensuring the sequence and correctness of data streams. Each data operation in the middle of TCP is equivalent to accessing a data stream. The most typical feature is the connection process of the three handshakes. The TCP connection establishment and revocation process is as follows:

 

Server

The main task of the Server side is to establish a communication endpoint and wait for the request sent by the client. The typical process is as follows:

1. Build a ServerSocket instance and specify the local port. This socket is used to listen to connection requests on the specified port.

2. Repeat the following steps:

A. Call the socket accept () method to obtain the connection request of the following client. The socket instance returned by the accept () method establishes a new connection with the client.

B. Use the returned socket instance to obtain InputStream and OutputStream. You can use these two streams to read and write data respectively.

C. Call the close () method of the socket instance to close the socket connection at the end.

 

The typical sample code for this process is as follows:

 

Java code
  1. // 1. Construct a ServerSocket instance and specify the service port.
  2. ServerSocket servSock = new ServerSocket (servPort );
  3. While (true)
  4. {
  5. // 2. Call the accept method to establish a connection with the client
  6. Socket clntSock = servSock. accept ();
  7. SocketAddress clientAddress =
  8. ClntSock. getRemoteSocketAddress ();
  9. System. out. println ("Handling client at" + clientAddress );
  10. // 3. Get the connected InputStream and OutputStream for data read/write
  11. InputStream in = clntSock. getInputStream ();
  12. OutputStream out = clntSock. getOutputStream ();
  13. While (recvMsgSize = in. read (receiveBuf ))! =-1)
  14. {
  15. Out. write (receiveBuf, 0, recvMsgSize );
  16. }
  17. // 4. The operation is complete. Disable socket.
  18. ClntSock. close ();
  19. }

 

Client

The client request process is slightly different:

1. Build a Socket instance and establish a connection through the specified remote server address and port.

2. Read and Write data through the InputStream and OutputStream contained in the Socket instance.

3. After the operation is complete, call the close method of the socket instance to close it.

The sample code is as follows;

 

Java code
  1. // 1. Establish a socket connection based on the specified server address and port.
  2. Socket socket = new Socket (server, servPort );
  3. // 2. Obtain InputStream and OutputStream Based on the socket instance for data read and write.
  4. InputStream in = socket. getInputStream ();
  5. OutputStream out = socket. getOutputStream ();
  6. Out. write (data );
  7. // 3. The operation is complete. Disable socket.
  8. Socket. close ();

 

 

UDP

There are two typical differences between UDP and TCP. One is that it does not need to establish a connection, and the other is that it retains the message boundary in each message sent and received.

Server

Because UDP does not need to establish a connection, the process is as follows:

1. Construct an initramsocket instance and specify the local port.

2. Use the receive method of the initramsocket instance to receive the contents of the communication in the middle of DatagramPacket. DatagramPacket.

3. Use the send and receive methods of mongoramsocket to receive and send mongorampacket.

The typical Interaction Process Code is as follows:

 

 

Java code
  1. // 1. Create an initramsocket instance and specify the local port.
  2. DatagramSocket socket = new DatagramSocket (servPort );
  3. // 2. Construct the initrampacket packet to be sent and received
  4. DatagramPacket packet = new DatagramPacket (new byte [ECHOMAX], ECHOMAX );
  5. While (true)
  6. {
  7. // 3. receive the message
  8. Socket. receive (packet );
  9. System. out. println ("Handling client at" + packet. getAddress (). getHostAddress ()
  10. + "On port" + packet. getPort ());
  11. // 4. Send messages
  12. Socket. send (packet );
  13. Packet. setLength (ECHOMAX );
  14. }

 

 

Client

The steps of the UDP client are also relatively simple, mainly including the following three steps:

1. Construct an initramsocket instance.

2. send the mongorampacket packet through the send and receive methods of the mongoramsocket instance.

3. Call the close method of DatagramSocket to close the interface.

Different from TCP, UDP can send packets to different servers at Will on the same local port. Generally, you do not need to specify the address of the target server in the UDP DatagramSocket constructor.

In addition, another important difference between the UDP client is that after the TCP client sends an echo connection message, it will be blocked when the read method is called, But UDP does not. Because UDP allows packet loss in the middle. If the packet is lost and the process is blocked or suspended, the process will never be able to go down. Therefore, a setSoTimeout method is usually set to specify how long the message will be discarded if it is not received. You can also specify a number and the number of times specified by the loop to read the message. If the number is read, the message is returned. Otherwise, the message is discarded.

 

A typical UDP Client code example is as follows:

 

Java code
  1. // 1. Construct a UDP DatagramSocket object
  2. DatagramSocket socket = new DatagramSocket ();
  3. // 2. Specifies the timeout time to prevent infinite wait
  4. Socket. setSoTimeout (TIMEOUT );
  5. // 3. Construct the packet object for sending and receiving
  6. DatagramPacket sendPacket = new DatagramPacket (bytesToSend,
  7. BytesToSend. length, serverAddress, servPort );
  8. DatagramPacket extends epacket =
  9. New DatagramPacket (new byte [bytesToSend. length], bytesToSend. length );
  10. // 4. specify the number of attempts
  11. Int tries = 0;
  12. Boolean receivedResponse = false;
  13. Do
  14. {
  15. Socket. send (sendPacket );
  16. Try
  17. {
  18. Socket. receive (paiepacket );
  19. If (! ReceivePacket. getAddress (). equals (serverAddress ))
  20. {
  21. Throw new IOException ("Received packet from an unknown source ");
  22. }
  23. ReceivedResponse = true;
  24. }
  25. Catch (InterruptedIOException e)
  26. {
  27. Tries + = 1;
  28. System. out. println ("Timed out," + (MAXTRIES-tries) + "");
  29. }
  30. } While ((! ReceivedResponse) & (tries <MAXTRIES ));
  31. // Provide feedback based on whether packets are received
  32. If (receivedResponse)
  33. {
  34. System. out. println ("Received:" + new String (paiepacket. getData ()));
  35. }
  36. Else
  37. {
  38. System. out. println ("No response -- giving up .");
  39. }
  40. // 5. Disable socket
  41. Socket. close ();
Summary

The Communication Between TCP server and client is like two people making calls. They need to know each other's phone number and start the conversation. Therefore, you must specify the port and address during the connection process.

The communication between UDP server and client is like two people sending messages to each other. I only need to know the address of the other party, and then send the mail. I don't know if the other party has received it, nor do I need to establish a connection with a password.

These examples are actually the simplest. A single thread can only process a single request at a time. In practical applications, it is generally applied to multithreading and some highly concurrent processing policies, such as event-driven reactor mode. You can discuss it in detail in subsequent articles.

References

1. TCP/IP Sockets in Java

2. TCP/IP encrypted strated, Volume 1: The Protocols (2nd Edition)
What is the relationship between SOCKET and TCP and UDP?

SOCKET is an API for Java to implement data communication.
This term originated from BSD-related UNIX and is the name of the API used for communication between processes in program development.

TCP/UDP is the two communication modes defined in Layer 4 of the OSI model.

That is to say, SOCKET is an API, and TCP/UPD is a communication protocol. The two are fundamentally different.

Example of language expression:
Use SOCKET to implement TCP (or UDP) communication. (On the contrary, TCP or UDP communication can also be implemented without SOCKET)

How does java reflect the difference in tcp programming udp programming?

The current computer configuration is high, so you don't have to worry too much about memory and resources. I recommend using tcp to transmit data. Although udp is fast, data loss is a big defect and tcp stability is still possible.

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.