1 Timeouts
The socket base is TCP-based, so the timeout for the socket and the TCP timeout are the same. The socket read-write buffer is discussed below, followed by the connection establishment timeout, read-write timeout, and nested exception captures for Java socket programming and a sample grab for a timeout example program.
Once a socket instance is created, the operating system allocates buffers for it to hold the data that is received and to be sent.
(1) Socket read-write buffer
Java can set the read-write buffer size-setreceivebuffersize (int size), setsendbuffersize (int size). Writing data to the output stream does not mean that the data has actually been sent, they are simply copied to the send buffer queue sendq, or the flush () method is raised in the socket's outputstream, nor does it guarantee that the data can be sent immediately to the network. The real data is sent by the operating system's TCP stack module from the buffer to send data to the network to complete. When there is data coming from the network, the TCP stack module receives the data and puts it into the receive buffer queue RECVQ, and the input stream inputstream the data out of the RECVQ through the Read method.
(2) Socket Connection Setup Timeout
The socket connection establishment is a TCP-based connection establishment process. The TCP connection needs to be completed by 3 handshake messages, a synchronous SYN message needs to be sent when the TCP connection is started, and then the acknowledgment message is Syn+ack, and then the ACK is sent. TCP connection is closed by 4 waves to complete, the side of the active shutdown TCP connection to send fin messages, waiting for the other party's confirmation message, the passive closed side also send fin message, wait for confirmation message.
There is a fixed-length connection queue waiting on one end of the TCP connection request, and the connection in the queue has been accepted by TCP (that is, the three handshake has been completed), but it has not yet been accepted by the application layer. TCP accepts a connection by placing it in the connection queue, and the application layer accepts the connection to remove it from the queue. The application layer can set the backlog variable to indicate the maximum length of the connection queue, which is the maximum number of connections that have been accepted by TCP waiting for the application tier to accept. When a connection request SYN arrives, TCP determines whether to accept the connection. If there is space in the queue, the TCP module confirms the SYN and completes the connection creation. However, the application layer will not know the new connection until the third message in the three handshake is received. If the queue has no space, TCP will ignore the received Syn. If the application tier does not accept connections that have been accepted by TCP in a timely manner, these connections may fill the entire connection queue, and new connection requests may not respond and time out. If a connection request SYN Send, after a period of time not received confirmation SYN+ACK,TCP will retransmit the connection request Syn two times, each retransmission time interval doubled, in the specified time still not received syn+ack,tcp will abandon this connection request, connection establishment timed out.
The JAVA socket connection establishment timeout is the same as TCP, and if the TCP three handshake times out when the connection is established, the socket connection establishment also expires. You can set the time-out for the socket connection setting-
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 three handshake times, then the socket connection will never be established.
Importjava.net.*;ImportJava.io.*; Public classsocketclienttest{ Public Static Final intPORT = 8088; Public Static voidMain (string[] args)throwsException {inetaddress addr= Inetaddress.getbyname ("127.0.0.1" ); Socket Socket=NewSocket (); Try{socket.connect (NewInetsocketaddress (addr, PORT), 30000 ); Socket.setsendbuffersize (100); BufferedWriter out=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); inti = 0; while(true) {System.out.println ("Client Sent---hello * * *" + i++ ); Out.write ("Client Sent---hello * * *" +i); Out.flush (); Thread.Sleep (1000 ); } } finally{socket.close (); } }}
(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 time-out period, and if there is still no data at the time-out, read throws a sockettimeoutexception, and the program needs to catch the exception. However, the current socket connection is still valid. If the opponent process crashes, the other machine restarts abruptly, the network disconnects, and the read on this side is blocked, it is very important to set the timeout time, otherwise the thread that calls read will always hang. The TCP module puts the received data into the RECVQ until the application layer invokes the Read method of the input stream for reading. If the RECVQ queue is filled, TCP notifies the other party not to continue sending the data based on the sliding window mechanism, which stops receiving data sent from the peer until the recipient application calls the Read method of the input stream to free up space.
Let's say we need to control how our clients interrupt blocking if they haven't read the data for 10 seconds before they start reading the data, we can do this:
Public classClient { Public Static voidMain (String args[])throwsException {//for the sake of simplicity, all exceptions are thrown directly outString host = "127.0.0.1";//Service-side IP address to connect to intPort = 8899;//the listener port for the server to which you want to connect//establish a connection to the serverSocket client =NewSocket (host, Port); //Once the connection is established, the data can be written to the server.Writer writer =NewOutputStreamWriter (Client.getoutputstream ()); Writer.write ("Hello Server."); Writer.write ("Eof\n"); Writer.flush (); //read after you finish writingBufferedReader br =NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); //set the timeout time to 10 secondsClient.setsotimeout (10*1000); StringBuffer SB=NewStringBuffer (); String temp; intindex; Try { while((Temp=br.readline ())! =NULL) { if(index = Temp.indexof ("EOF"))! =-1) {sb.append (temp.substring (0, index)); Break; } sb.append (temp); } } Catch(sockettimeoutexception e) {System.out.println ("Data read timed out." "); } System.out.println ("From server:" +SB); Writer.close (); Br.close (); Client.close (); }}
2 disconnecting
The TCP socket connection is bidirectional and is broken by four waves , each of which calls the Socket.close() method to disconnect. In the process of disconnection, the general party a first disconnects, and the other party B discovers a disconnects, and disconnects. For convenience, a disconnected party A is referred to as an "active disconnection", and a "passive disconnect"is the one on the other side after disconnecting the party B.
When a party B blocks the execution in.readUTF() method, this method throws an exception if the other party a actively disconnects the socket. In order to handle the exception in B, you can passively disconnect this connection.
To ensure that a party that is actively disconnected is not blocked in the in.readUTF() method, it needs to be executed first socket.shutdownInput() . So the code for the active disconnection is as follows.
Socket.shutdowninput (); In.close (); Socket.close ();
A passive disconnected party, caught in.readUTF() in a after the exception, disconnect the socket connection.
Try=catch (IOException e) {// connection disconnected (passive)try nullnullcatch (IOException e) {e.printstacktrace () ;}}
Java Socket (2): Exception handling