Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the timeout Analysis of Java Socket

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what the timeout analysis of Java Socket is, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

A socket or socket (socket) is a software form of abstraction used to express a "terminal" of a connection between two machines. There is a "socket" on each machine for a particular connection, and you can imagine a virtual "cable" between them. JAVA has two data flow-based socket classes: ServerSocket, which the server uses to "listen" for incoming connections, and Socket, which is used by clients to make an initial connection. Listening sockets can only receive new connection requests, not actual packets.

Socket is implemented based on TCP/IP, which is used to provide a service interface to access TCP, or socket socket is TCP's application programming interface API, through which the application layer can access the services provided by TCP.

In JAVA, we create a socket connection with the ServerSocket and socket classes, and the result from the socket is an InputStream and OutputStream object to treat the connection as an IO stream object. Through the IO stream, you can read data from the stream or write data to the stream, and abnormal IOException will be generated when reading and writing IO streams.

The underlying socket is based on TCP, so the socket timeout is the same as the TCP timeout. Let's first discuss the socket read-write buffer, and then discuss connection establishment timeout, read-write timeout, nested exception capture in JAVA socket programming and packet capture examples of a timeout example program.

1. Socket read-write buffer

Once a socket instance is created, the operating system allocates a buffer to hold the data received and sent.

JAVA can set the size of the read-write buffer-setReceiveBufferSize (int size), setSendBufferSize (int size).

Writing data to the output stream does not mean that the data has actually been sent; it is simply copied to the send buffer queue SendQ, which calls the flush () method on Socket's OutputStream, and there is no guarantee that the data will be sent to the network immediately. The real data transmission is accomplished by the TCP protocol stack module of the operating system, which takes data from the buffer and sends it to the network.

When data arrives from the network, the TCP protocol stack module receives the data and puts it into the receiving buffer queue RecvQ, and the input stream InputStream takes the data from the RecvQ through the read method.

2. Socket connection establishment timeout

Socket connection establishment is a connection establishment process based on TCP. The connection of TCP needs to be completed by three handshakes. When you start to establish a TCP connection, you need to send a synchronous SYN message, and then wait for the confirmation message SYN+ACK,*** to send the confirmation message ACK. The closure of the TCP connection is completed through four waves. The party who actively closes the TCP connection sends a FIN message and waits for the other party's confirmation message; the passively closed party also sends the FIN message and waits for the confirmation message.

There is a fixed-length connection queue at the end waiting for the TCP connection request, and the connection in this queue has been accepted by TCP (that is, the three-way handshake has been completed), but not by the application layer. TCP accepts a connection by putting it in the connection queue, while the application layer accepts the connection by removing it from the queue. The application layer can specify the * length of the connection queue by setting the backlog variable, that is, the number of * connections that have been accepted by TCP while waiting for the application layer to accept.

When a connection request SYN arrives, the TCP determines whether to accept the connection. If there is still room in the queue, the TCP module acknowledges the SYN and completes the connection. However, the application layer will not know about the new connection until the third message in the three-way handshake is received. If there is no space in the queue, TCP ignores the SYN received.

If the application layer cannot accept connections that have been accepted by TCP in time, these connections may fill the entire connection queue, and new connection requests may time out without response. If a connection request SYN is sent and does not receive an acknowledgement after a period of time, the SYN+ACK,TCP will retransmit the connection request SYN twice, and the interval between each retransmission is doubled. If the connection request will be abandoned by SYN+ACK,TCP within the specified time, the connection establishment timeout will occur.

The JAVA Socket connection establishment timeout is the same as TCP. If the TCP three-way handshake times out when establishing a connection, it will cause the Socket connection establishment to time out. You can set the timeout for establishing a Socket connection-

Connect (SocketAddress endpoint, int timeout)

If the connection is not established successfully within the timeout, the TimeoutException exception is thrown. If the value of timeout is less than the time of the three-way handshake, the Socket connection will never be established.

Different application layers have different connection establishment processes. Socket connection establishment is the same as TCP-only a three-way handshake is needed to complete the connection, but some applications need to interact a lot of information before successfully establishing a connection, such as the Telnet protocol. After the TCP three-way handshake is completed, Telnet connections need to be negotiated.

3. Socket read timeout

If there is no data in the input buffer queue RecvQ, the read operation will block and suspend the thread until new data arrives or an exception occurs. Call setSoTimeout (int timeout) to set the timeout. If there is no data at the timeout, read will throw a SocketTimeoutException. The program needs to catch this exception, but the current socket connection is still valid.

If the other party's process crashes, the other machine suddenly restarts, and the network is disconnected, the local read will continue to block, so it is very important to set the timeout, otherwise the thread calling read will hang all the time.

The TCP module puts the received data into the RecvQ until the application layer calls the read method of the input stream to read it. If the RecvQ queue is full, the TCP will notify the other party not to continue sending data according to the sliding window mechanism, and the local side will stop receiving the data sent from the opposite end until the receiver application calls the read method of the input stream to make room.

4. Socket write timeout

The write timeout of socket is based on the retransmission of TCP timeout. Timeout retransmission is an important mechanism for TCP to ensure reliable data transmission. Its principle is to start a timer after sending a data message, and resend the message if it does not get the acknowledgement ACK within a certain period of time. If there is still no acknowledgement message after multiple retransmissions, a reset message RST is sent, and then the TCP connection is closed. The time difference between data message transmission and reset message transmission is about 9 minutes, that is, if no acknowledgement message is received within 9 minutes, the connection is closed. However, this value varies depending on the implementation of the TCP stack.

If the sender calls write, it continues to write out the data until the SendQ queue is filled. If the write method is called when the SendQ queue is full, the write will be blocked until the SendQ has new free space, that is, until some bytes have been transferred to the RecvQ of the receiver socket. If the RecvQ queue is also full at this time, all operations will stop until the receiver calls the read method to transfer some bytes to the application.

When the write of Socket sends data, if the network cable is disconnected, the peer process crashes, or the peer machine restarts, the TCP module will retransmit the data and close the connection when it times out. The next time you call write, it will cause an exception and exit.

Socket write timeout is a timeout retransmission mechanism based on TCP protocol stack, which generally does not need to set write timeout, nor does it provide such a method.

5. Double nested exception capture

If the construction of ServerSocket or Socket fails, you only need to catch the construction failure exception and do not need to call the socket's close method to release resources (you must ensure that no resources need to be cleared after the construction failure), because the socket internal resources are not allocated successfully. If the construction is successful, you must go into a block of try finally statements and call close to release the socket. Please refer to the following example program.

Import java.net.*; import java.io.*; public class SocketClientTest {public static final int PORT = 8088; public static void main (String [] args) throws Exception {InetAddress addr = InetAddress.getByName ("127.0.0.1"); Socket socket = new Socket (); try {socket.connect (new InetSocketAddress (addr, PORT), 30000); socket.setSendBufferSize BufferedWriter out = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream ())); int I = 0; while (true) {System.out.println ("client sent-- hello * *" + I); out.write ("client sent-hello * *" + I); out.flush () Thread.sleep (1000);}} finally {socket.close ();} import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class SocketServerTest {public static final int PORT = 8088; public static final int BACKLOG = 2; public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (PORT, BACKLOG) System.out.println ("started:" + server); try {Socket socket = server.accept (); try {BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ())); String info = null; while ((info = in.readLine ())! = null) {System.out.println (info) }} finally {socket.close ();}} finally {server.close ();}

Execute the above program, after the program runs for a while, disconnect the network connection between client and server, and output the following on the machine:

Output on Server:

Echoing:client sent-hello0Echoing:client sent-hello1Echoing:client sent-hello2Echoing:client sent-hello3Echoing:client sent-hello4Echoing:client sent-hello5Echoing:client sent-hello6

-> > No data output after disconnecting the network

Output on Client:

Socket default timeout = 0socket = Socket [addr=/10.15.9.99,port=8088,localport=4691] begin to readclient sent-hello * 0client sent-hello * 1client sent-hello * 2client sent-- hello * 3client sent-hello * * 4client sent-hello * 5client sent-- hello * 6client sent-- hello * * 7client sent-- hello * 8 client sent-- hello * * 9client sent-hello * * 10

-> > client process hangs after disconnecting from the network

Java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0 (Native Method) at java.net.SocketOutputStream.socketWrite (SocketOutputStream.java:92) at java.net.SocketOutputStream.write (SocketOutputStream.java:136) at sun.nio.cs.StreamEncoder.writeBytes (StreamEncoder.java:202) at sun.nio.cs.StreamEncoder.implFlushBuffer (StreamEncoder.java:272) at sun.nio.cs.StreamEncoder.implFlush (StreamEncoder . Java: 276) at sun.nio.cs.StreamEncoder.flush (StreamEncoder.java:122) at java.io.OutputStreamWriter.flush (OutputStreamWriter.java:212) at java.io.BufferedWriter.flush (BufferedWriter.java:236) at com.xtera.view.SocketClientTest.main (SocketClientTest.java:99)

When the hello6 is sent to the server, the network connection is disconnected, and the server cannot receive any data and hangs. The client side continues to send data. In fact, hello7, hello8, hello9, and hello10 are all copied to the SendQ queue, and the write method returns immediately. When the SendQ queue for client is filled, the write method is blocked. After sending the message hello7, the TCP module time-out retransmits without receiving an acknowledgement, and closes the TCP connection after several retransmissions, resulting in an abnormal return of the blocked write method.

Through the packet grabbing tool, we can see the message that is retransmitted in time out.

Time-out analysis on Java Socket what is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report