In the previous article, we discussed the basic usage of the Socket class. In the example given, the Socket class is used to connect to the server with the simplest connection method, that is, connect to the server through the IP address and port number. To make the method of connecting to the server more flexible, the Socket class can not only connect to the server through its own constructor, but also connect to the database through the connect method.
1. Connect to the server through Constructor
We can use six overload constructors to connect to the server in different ways. These six overloaded constructors can be divided into two types:
1. automatically select IP
This method is the most common. Automatic IP selection means that when the local machine has multiple NICs or multiple IP addresses are bound to one Nic, the Socket class will automatically select an available IP address for us. Four of the above six constructor methods use this method to connect to the server.
<! -- [If! SupportLists] --> (1) <! -- [Endif] --> public Socket (String host, int port)
This is the most common constructor, which is used in the previous example. You only need to provide a string type IP address or domain name and an integer port number. This constructor may throw two errors: UnknownHostException and IOException. The first error occurs because the host we provide does not exist or is invalid, and other errors are classified as IO errors. Therefore, the complete definition of this constructor is:
Public Socket (String host, int port) throws UnknownHostException, IOException
(2) public Socket (InetAddress inetaddress, int port)
This constructor is similar to the first constructor, except that the host in string form is changed to the InetAddress object type. In this constructor, The InetAddress class is used mainly because the Socket class may need to be used in the program to connect to the same IP address or domain name multiple times. In this way, the efficiency of using the InetAddress class is relatively high. In addition, two errors may occur when you use a string-type host to connect to the server. However, if you use the InetAddress object to describe the host, only the IOException error occurs, this is because when you pass the IP address or domain name to InetAddress, InetAddress will automatically check this IP address or domain name. If this IP address or domain name is invalid, InetAddress will throw the UnknownHostException error, instead of being thrown by the Socket class constructor. Therefore, the complete definition of this constructor is:
Public Socket (InetAddress inetaddress, int port) throws IOException
(3) public Socket (String host, int port, boolean stream)
This constructor method is similar to the first constructor method. It only adds a boolean stream parameter. If this stream is true, the constructor is exactly the same as the first constructor. If stream is false, a UDP connection is established using the UDP protocol, here, we only need to know that the biggest difference between UDP and TCP is that UDP is connectionless, while TCP is connectionless ), maybe Sun's developers did not consider writing the initramsocket class for processing UDP connections when writing the Socket class, so they added the UDP connection establishment function to the Socket class, however, Sun added the initramsocket class to the later JDK, so this constructor is useless. Therefore, Sun sets it as the Deprecated mark, that is, this constructor can be deleted in later JDK versions. For the above reason, when using Java to write network programs, try not to use this constructor to establish UDP connections.
(4) public Socket (InetAddress inetaddress, int port, boolean flag)
This constructor has the same meaning as the flag mark of the third constructor and is not recommended.
The following code demonstrates the use of the above four constructor methods:
Package mysocket;
Import java.net .*;
Import java. io .*;
Public class MoreConnection
{
Private static void closeSocket (Socket socket)
{
If (socket! = Null)
Try
{
Socket. close ();
}
Catch (Exception e ){}
}
Public static void main (String [] args)
{
Socket socket1 = null, socket2 = null, socket3 = null, socket4 = null;
Try
{
// If you change www.ptpress.com.cn to another domain name that does not exist, the UnknownHostException error will be thrown.
// Test public Socket (String host, int port)
Socket1 = new Socket ("www.ptpress.com.cn", 80 );
System. out. println ("socket1 connection successful! ");
// Test public Socket (InetAddress inetaddress, int port)
Socket2 = new Socket (InetAddress. getByName ("www.ptpress.com.cn"), 80 );
System. out. println ("socket2 connection successful! ");
// The following two connection establishment methods are not recommended
// Test public Socket (String host, int port, boolean stream)
Socket3 = new Socket ("www.ptpress.com.cn", 80, false );
System. out. println ("socket3 connection successful! ");
// Test public Socket (InetAddress inetaddress, int I, boolean flag)
Socket4 = new Socket (InetAddress. getByName ("www.ptpress.com.cn"), 80, false );
System. out. println ("socket4 connection successful! ");
}
Catch (UnknownHostException e)
{
System. out. println ("UnknownHostException is thrown! ");
}
Catch (IOException e)
{
System. out. println ("IOException thrown! ");
}
Finally
{
CloseSocket (socket1 );
CloseSocket (socket2 );
CloseSocket (socket3 );
CloseSocket (socket4 );
}
}
}
In the code above, finally closed the opened Socket connection. This is a good habit. This is because the code that closes the Socket connection is only written in finally, regardless of whether an error occurs. However, before closing the Socket connection, you must check whether the Socket object is null. This is because an error may occur when the connection is established, so that the Socket object is not successfully established, you don't need to close it.
1. Manually bind an IP address
When the local machine has multiple IP addresses (these IP addresses may be on multiple NICs or multiple IP addresses bound to one Nic ), when connecting to the server, the client needs to determine which IP address to use. In this way, the other two construction methods of the Socket class must be used for processing. Let's take a look at how these two constructor uses a specific IP address to connect to the server.
Public Socket (String host, int port, InetAddress inetaddress, int localPort)
The parameters of this constructor are divided into two parts. The first part is the first two parameters: host and port, which respectively indicate the IP address and port number of the server to be connected. The second part is the last two parameters: inetaddress and localPort. Inetaddress indicates the local IP address to be used, while localPort indicates the local port number to be bound. This localPort is set to any unbound port number on the local machine. If you set the localPort value to 0, jav