AndServerSocketThere are two types of Object-related information: binding port and bindingIPAddress. You can useGetLocalPortMethod. BindIPYou can useGetInetAddressMethod.
I,GetLocalPortMethod
GetLocalPortThe return values of a method can be divided into the following three situations:
1.ServerSocketThe object is not bound to a port,GetLocalPortThe Return Value of the method is-1.
2.ServerSocketThe object is bound to a fixed port,GetLocalPortMethod to return this fixed port.
3. ServerSocketThe binding port of the object is0,GetLocalPortMethod returns a random port (this type of port is called an anonymous port ).
GetLocalPortThe method is defined as follows:
Public Int GetLocalPort ()
GetLocalPortThe method is mainly for these anonymous ports. The following codeDemonstratedServerSocketThe process of generating random ports for objects:
Package Server;
Import Java.net. * ;
Public Class RandomPort
{
Public Static Void Main (String [] args) Throws Exception
{
For ( Int I = 1 ; I <= 5 ; I ++ )
{
System. out. print ( " Random Port " + I + " : " );
System. out. println ( New ServerSocket ( 0 ). GetLocalPort ());
}
}
}
Running result:
Randport1: 1397
Random Port2: 1398
Random Port3: 1399
Random Port4: 1400
Random Port5: 1401
In most cases, the ServerSocket object is bound to a fixed port. However, sometimes the client only needs to connect to the server for a short period of time, then the anonymous port can be used. For example, we often use the FTP service.