Binding a port through constructor is the most common method for creating a serversocket object:
Public serversocket (INT port) throws ioexception
If the port specified by the port parameter has been bound, the constructor will throw an ioexception, but the actually thrown exception is bindexception. Because network-related exceptions are subclasses of the ioexception class, ioexception is used for the serversocket constructor to throw other exceptions.
If the port value is 0, the system selects a random port number, but the randomly selected port does not make sense, 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.
Serversocket = new serversocket (1320 );
System. Out. println (serversocket );
Running result:
Serversocket [ADDR = 0.0.0.0/0.0.0.0, Port = 0, localport = 1320]
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. The port is always 0; localport is the port bound to serversocket. If the parameter port value is 0, 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.
Determine which ports are opened on the local machine: 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 is not opened.