Java Network Programming from entry to entry (29): server Socket option

Source: Internet
Author: User

The ServerSocket class has the following three options:

1. SO_TIMEOUT: Set the timeout value of the accept method.

2. SO_REUSEADDR: Set whether the same port on the server can be bound multiple times.

3. SO_RECBUF: set the size of the receiving buffer.

I. SO_TIMEOUT Option

You can set and obtain the value of the SO_TIMEOUT option through two SeverSocket methods (setSoTimeout and getSoTimeout). The two methods 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 indicates the time-out time of the accept method, in milliseconds. Normally, the ServerSocket accept method is in the infinite waiting status when waiting for client requests. For example, the HTTP server will always wait for user requests when no user accesses the webpage. Generally, you do not need to set the wait time-out period for the client. However, in some special cases, the server requires that the client must send a request to the server within a certain period of time. In this case, you need to set the wait time-out period for the client request, that is, the timeout time of the accept method. When the client request times out, the accept method throws a SocketTimeoutException exception after waiting for the time-out. The following code demonstrates how to set and obtain the value of the SO_TIMEOUT option. The timeout value is passed into the AcceptTimeout using the command line parameter.


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 )? "The accept method will be in"
+ ServerSocket. getSoTimeout () + "an exception is thrown in milliseconds! ":" The accept method is always blocked! ");;
ServerSocket. accept ();
}
}

Run the following command:


Java server. AcceptTimeout 3000

Running result:

The accept method will throw 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 called before the ServerSocket object is bound to a port, or after the port is bound. The following code is correct:

ServerSocket serverSocket = new ServerSocket ();
ServerSocket. setSoTimeout (3000 );
ServerSocket. bind (new InetSocketAddress (1234 ));

Ii. SO_REUSEADDR Option

The SO_REUSEADDR option determines whether a port can be bound multiple times. You can use the setReuseAddres and getReuseAddress methods of the SeverSocket class to set and obtain the value of the SO_TIMEOUT option. The two methods are defined as follows:


Public void setReuseAddress (boolean on) throws SocketException
Public boolean getReuseAddress () throws SocketException


In most operating systems, a port cannot be bound multiple times. If a ServerSocket object is bound to an occupied port, the ServerSocket constructor or bind method throws a BindException exception.

Java provides this option to prevent the system from working properly due to frequent binding and releasing a fixed port. After the ServerSocket object is closed, if there is still unprocessed data in the ServerSocket object, the port bound to it may not be released for a period of time. This will cause other ServerSocket objects to be unable to bind this port. When setting this option, if a port is bound for the first time, you do not need to call the setReuseAddress method. When you bind the port again, you must use the setReuseAddress method to set this option to true. This method must be called before the bind method is called. The following code demonstrates how to set and obtain the value of this option:


Package server;

Import java.net .*;

Public class TestReuseAddr1
{
Public static void main (String [] args) throws Exception
{
ServerSocket serverSocket1 = new ServerSocket (1234 );
System. out. println (serverSocket1.getReuseAddress ());

ServerSocket serverSocket2 = new ServerSocket ();
ServerSocket2.setReuseAddress (true );
ServerSocket2.bind (new InetSocketAddress (1234 ));

ServerSocket serverSocket3 = new ServerSocket ();
ServerSocket3.setReuseAddress (true );
ServerSocket3.bind (new InetSocketAddress (1234 ));
}
}


Running result: false


In the code above, port 1234 is bound for the first time. Therefore, the serverSocket1 object does not need to be set with the SO_REUSEADDR option (the default value of this option on most operating systems is false ). ServerSocket2 and serverSocket3 are not bound to port 1234 for the first time. Therefore, the SO_REUSEADDR value of these two objects must be set to true. When setting the SO_REUSEADDR option, note that this option must be set before the ServerSocket object is bound to a port.

Some readers may have such questions. If multiple ServerSocket objects are bound to one port at the same time, which ServerSocket object should receive client requests when the client sends a request to this port? Before giving the answer, let's take a look at the output results of the following code.


Package server;

Import java.net .*;

Public class TestReuseAddr2 extends Thread
{
String s;
Public void run ()
{
Try
{
ServerSocket serverSocket = new ServerSocket ();
ServerSocket. setReuseAddress (true );
ServerSocket. bind (new InetSocketAddress (1234 ));
Socket socket = serverSocket. accept ();
System. out. println (s + ":" + socket );
Socket. close ();
ServerSocket. close ();
}
Catch (Exception e)
{
}
}
Public TestReuseAddr2 (String s)
{
This. s = s;
}
Public static void main (String [] args)
{
For (int I = 1; I <= 5; I ++)
New TestReuseAddr2 ("ServerSocket" + I). start ();
}
}

 

Run the following command:

Java server. TestReuseAddr2


Run the following command five times in a row:


Telnet local host 1234

Execution result:


ServerSocket1: Socket [addr =/127.0.0.1, port = 11724, localport = 1234]
ServerSocket3: Socket [addr =/127.0.0.1, port = 11725, localport = 1234]
ServerSocket5: Socket [addr =/127.0.0.1, port = 11726, localport = 1234]
ServerSocket2: Socket [addr =/127.0.0.1, port = 11727, localport = 1234]
ServerSocket4: Socket [addr =/127.0.0.1, port = 11728, localport

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.