The ServerSocket class has the following three options:
1.so_timeout: Sets the timeout time for the Accept method.
2.SO_REUSEADDR: Sets whether the same port on the server can be bound multiple times.
3.SO_RECBUF: Sets the size of the receive buffer.
First, so_timeout options
You can set and get the values of the So_timeout option by using the two methods of the Seversocket class (Setsotimeout and Getsotimeout), which are defined as follows:
public synchronized void setSoTimeout(int timeout) throws SocketException
public synchronized int getSoTimeout() throws IOException
The timeout parameter of the Setsotimeout method represents the time-out time, in milliseconds, of the Accept method. In general, the accept method of the ServerSocket class is in an infinite wait state while waiting for a client request. An HTTP server waits for a user's request when no user accesses the Web page. Generally, there is no need to wait for client requests to timeout on the server side, but in some special cases, the server requires the client to make a request to the server at a certain time, then set the wait client request timeout, that is, the Accept method timeout. After the client request timeout is set, the Accept method throws a Sockettimeoutexception exception after the wait timeout. The following code shows how to set and get the value of the So_timeout option, which is passed through command-line arguments to the accepttimeout.
package server;
import java.net.*;
public class AcceptTimeout
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
return;
ServerSocket serverSocket = new ServerSocket(1234);
int timeout = Integer.parseInt(args[0]);
serverSocket.setSoTimeout(Integer.parseInt(args[0]));
System.out.println((timeout > 0) ? "accept方法将在"
+ serverSocket.getSoTimeout() + "毫秒后抛出异常!" : "accept方法永远阻塞!");;
serverSocket.accept();
}
}
Execute the following command:
Java server. Accepttimeout 3000
Run Result:
The Accept method throws an exception after 3000 milliseconds!
Exception in thread "main" java.net.SocketTimeoutException: Accept timed out
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:384)
at java.net.ServerSocket.implAccept(ServerSocket.java:450)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at chapter5.AcceptTimeout.main(AcceptTimeout.java:16)
The Setsotimeout method can be invoked before the ServerSocket object binds the port, and also after the port is bound. The following code is also correct:
ServerSocket serverSocket = new ServerSocket();
serverSocket.setSoTimeout(3000);
serverSocket.bind(new InetSocketAddress(1234));