Java Network Programming from entry to mastery (25): Create a ServerSocket object

Source: Internet
Author: User

The ServerSocket class constructor has four reloads. Their definitions are as follows:

Public ServerSocket () throws IOException
Public ServerSocket (int port) throws IOException
Public ServerSocket (int port, int backlog) throws IOException
Public ServerSocket (int port, int backlog, InetAddress bindAddr) throws IOException
The preceding constructor involves three parameters: port, backlog, and bindAddr. Specifically, port is the port to be bound to the ServerSocket object, backlog is the length of the Request queue, and bindAddr is the IP address to be bound to the ServerSocket object.

1. Bind a port through the constructor

Binding a port through constructor is the most common method for creating a ServerSocket object. You can bind a port by using the following constructor:

Public ServerSocket (int port) throws IOException
If the port specified by the port parameter has been bound, the constructor throws an IOException. But the exception actually thrown is BindException. From the inheritance relationship diagram of exception classes in Figure 4.2, we can see that all network-related exceptions are subclasses of the IOException class. Therefore, IOException is used to throw other exceptions for the ServerSocket constructor.

If the port value is 0, the system selects a random port number. However, the randomly selected port is of little significance, because the client needs to clearly know the port number of the server program when connecting to the server. You can use the toString method of ServerSocket to output information related to the ServerSocket object. The following code inputs information related to the ServerSocket object.

ServerSocket serverSocket = new ServerSocket (1320 );
System. out. println (serverSocket );
Running result:


ServerSocket [addr = 0.0.0.0/0.0.0.0, port = 0, localport = 1320]
In the above output result, addr is the IP address bound to the server. If no IP address is bound, this value is 0.0.0.0. In this case, the ServerSocket object listens to all IP addresses of all network interfaces on the server. Port is always 0. Localport is the port bound to ServerSocket. If the port value is 0 (not the output port, it is the parameter port of the ServerSocket constructor), localport is a randomly selected port number.

1 ~ in the operating system ~ 1023 indicates the port number used by the system. The minimum value of the port number is 1 and the maximum value is 65535. In Windows, you can bind a program with a port number less than 1024, but in Linux/Unix, you must use root login to bind a port less than 1024. In the previous article, we used the Socket class to determine which ports are opened on the local machine. In fact, the ServerSocket class can achieve the same purpose. The basic principle is to use ServerSocket to bind the local port. If a BindException exception is thrown when a port is bound, it indicates that the port has been opened. Otherwise, the port has not been opened.


Package server;

Import java.net .*;

Public class ScanPort
{
Public static void main (String [] args)
{
If (args. length = 0)
Return;
Int minPort = 0, maxPort = 0;
String ports [] = args [0]. split ("[-]");
MinPort = Integer. parseInt (ports [0]);
MaxPort = (ports. length> 1 )? Integer. parseInt (ports [1]): minPort;
For (int port = minPort; port <= maxPort; port ++)
Try
{
ServerSocket serverSocket = new ServerSocket (port );
ServerSocket. close ();
}
Catch (Exception e)
{
System. err. println (e. getClass ());
System. err. println ("port" + port + "enabled! ");
}
}
}


In the above Code, the information about the exception class thrown when the ServerSocket object is created is output. ScanPort uses the command line parameter to pass the range of port numbers to be scanned into the program. The parameter format is minPort-maxPort. If you only enter one port number, the ScanPort program only scans this port number.

Test

Java server. ScanPort 1-1023 running result
Class java.net. BindException
Port 80 is enabled!
Class java.net. BindException
Port 135 is enabled!
Ii. Set the length of the Request queue

When writing a server program, it generally processes multiple client requests simultaneously through multiple threads. That is to say, a thread is used to receive client requests. When a request is received (a Socket object is obtained), a new thread is created and the client request is handed over to the new thread for processing. The thread that receives client requests continues to receive client requests. The implementation code of this process is as follows:


ServerSocket serverSocket = new ServerSocket (1234); // bind the port
// Code for processing other tasks
While (true)
{
Socket socket = serverSocket. accept (); // wait for receiving client requests
// Code for processing other tasks
New ThreadClass (socket). start (); // create and run a thread that processes client requests
}
The ThreadClass class in the code above is a subclass of the Thread class. The constructor of this class has a Socket-type parameter. You can pass the Socket object into the ThreadClass object through the constructor, and process client requests in the run method of the ThreadClass object. This code looks like seamless on the surface. No matter how many client requests there are, as long as the server configuration is high enough, it can be processed. However, if you think carefully about the above Code, we may find some problems. If there is enough complex code in lines 2nd and 6th, the execution time is long, which means that the server program cannot respond to the client request in time.

Assume that the code for lines 2nd and 6th is Thread. sleep (3000), which will delay the program for 3 seconds. In these three seconds, the program will not execute the accept method. Therefore, this program only binds the port to 1234 and does not start to receive client requests. If a client sends a request to port 1234 at this time, in theory, the client should have a connection rejection error, but the client shows that the connection is successful. The reason is that the request queue to be discussed in this section is at work.

After a server socket object is bound to a port, the operating system will allocate a first-in-first-out queue for the port (the default queue length is generally 50 ), this queue is used to save unprocessed client requests, so it is called a request queue. The ServerSocket accept method reads unprocessed client requests from this queue. If the request queue is empty, accept is blocked. Each time a client sends a request to the server, the server first saves the client request in the Request queue, and then reads the accept from the request queue. This can also explain why the above Code can still receive a certain number of client requests without executing the accept method. If the number of client requests in the Request queue reaches the maximum capacity of the Request queue, the server will no longer be able to receive client requests. If the client sends another request to the server, the client will throw a SocketException.

The ServerSocket class has two constructor Methods: You can use the backlog parameter to reset the length of the Request queue. In the following situations, the maximum length of the Request queue is still limited by the operating system:

The backlog value is less than or equal to 0.
The value of backlog is greater than the maximum length of the Request queue defined by the operating system.
The backlog parameter is not set in the ServerSocket constructor.
The following area code demonstrates some features of the Request queue. The length of the Request queue is passed in to SetRequestQueue through the command line parameter.


Package server;

Import java.net .*;

Class TestRequestQueue
{
Public static void main (String [] args) throws Exception
{
For (int I = 0; I <10; I ++)
{
Socket socket = new Socket ("localhost", 1234 );
Socket. getOutputStream (). write (1 );
System. out. println ("created successfully" + String. valueOf (I + 1) + "client connection! ");
}
}
}
Public class SetRequestQueue
{
Public static void main (String [] args) throws Exception
{
If (args. length = 0)
Return;
Int queueLength = Integer. parseInt (args [0]);
ServerSocket serverSocket = new S

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.