Java network programming from getting started to mastering (14): A variety of ways to establish a network connection

Source: Internet
Author: User

In the previous article we discussed the basic use of the socket class, and given an example of using the socket class to connect to the server using the simplest connection, that is, by IP and port number to connect to the server. In order to make the connection server more flexible, the socket class can not only connect the server through its own construction method, but also can connect the database through the Connect method.

First, connecting to a server by constructing a method

We can connect to the server in a different way through 6 overloaded constructors. These 6 overloaded constructors can be divided into two categories: 1. Automatic IP selection is the most common method. The so-called auto-select IP refers to the socket class automatically chooses an available IP for us when there is more than one NIC or multiple IPs bound on a network card. Of the 6 construction methods mentioned above, there are 4 that use this method to connect to a server.

(1) public Socket (String host, int port)

This is the most common construction method, which is used in the previous example. You only need to provide a string type of IP or domain name and an integer port number when you use it. Two errors may be thrown in this construction method: Unknownhostexception and IOException. The first error occurred because the host we provided was not present or illegal, and the other errors were 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 construction method, except that the host in the form of a string is changed to the InetAddress object type. The reason for using the InetAddress class in this construction method is that the use of the InetAddress class is more efficient because it is possible to use the socket class to connect to the same IP or domain name multiple times in a program. In addition, there can be two errors when you connect to a server using a string-type host, but using the InetAddress object to describe the host only ioexception errors occur because when you pass an IP or domain name to inetaddress, InetAddress will automatically check this IP or domain name, if this IP or domain name is invalid, then inetaddress will throw a unknownhostexception error, not by the socket class construction method thrown. 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 method of construction is similar to the first construction method, except that it has a Boolean stream parameter. If this stream is true, then this constructor is exactly the same as the first method of construction. If stream is false, a UDP connection is established using the UDP protocol (UDP is discussed in detail in the following section, where it is only known that the biggest difference between it and TCP is that UDP is oriented to no connection, and TCP is oriented to connected). Perhaps the original sun developers in writing the socket class did not consider writing processing UDP connection Datagramsocket class, so the establishment of the UDP connection function into the socket class, However, Sun has added the Datagramsocket class to the later JDK, so the construction method is useless, so sun sets it to the deprecated tag, which means that this construction method can be removed in later JDK versions. For these reasons, try not to use this construction method to establish a UDP connection when writing a network program in Java.

(4) public Socket (inetaddress inetaddress, int port, Boolean flag)

This constructor is the same as the flag tag of the third construction method, and is not recommended for use .
The following code demonstrates the use of the above 4 construction 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 nonexistent domain name, 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 succeeded!");             //  Test PubLic socket (Inetaddress inetaddress, int port)              socket2 = new socket (Inetaddress.getbyname ("www.ptpress.com.cn"),  80);             SYSTEM.OUT.PRINTLN ("Socket2 connection succeeded!");
            //  the following two ways to establish a connection are not recommended for use with              //  Test Public socket (String host,  int port, boolean stream)              socket3 = new socket ("www.ptpress.com.cn",  80, false);             SYSTEM.OUT.PRINTLN ("Socket3 connection succeeded!");             //  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 succeeded!");                  catch  (unknownhostexception  e)         {             system.out.println ("unknownhostexception  is thrown!");                  catch  ( Ioexception e)         {             system.out.println ("ioexception  is thrown!");         }         finally          {             closesocket (SOCKET1);             closesocket (Socket2);              closesocket (SOCKET3);             closesocket (SOCKET4);         }     }}

It is a good practice to close the open socket connection at the end of the code above through finally. This code is executed only if the code that closes the socket is written in finally, whether it is an error or not. Note, however, that before you close the socket connection, you must check that the socket object is NULL, because the error is likely to occur when the connection is established so that the socket object is not successful and does not need to be closed.

1. Manually bind IP

When the machine has multiple IPs (which may be on multiple NICs or multiple IPs bound on a single NIC), the client needs to determine which IP to use when connecting to the server. This must be handled using two additional construction methods of the socket class. Let's look at how these two constructs are used to connect to the server using a specific IP .

Public Socket (String host, int port, inetaddress inetaddress, int localport)

The parameters of this constructor are divided into two parts, the first two parameters: Host and port, each representing the IP and port number of the server to be connected. The second part is divided into the latter two parameters: InetAddress and LocalPort. Where inetaddress represents the local IP to use, and LocalPort represents the local port number to bind. This localport this to any non-bound port number that is set to native. If you set the value of LocalPort to 0,java, an unbound port number will be selected between 1024 and 65,535. Therefore, the LocalPort is set to 0 under normal circumstances.

Public Socket (inetaddress inetaddress, int port, inetaddress inetaddress1, int localport)

This construction method is basically the same as the first one, except that the first parameter, host, is replaced with inetaddress. Other methods of use are similar to the first construction method.

The two construction methods are used in the following code to do an experiment. Let's assume there are two computers: PC1 and PC2. PC1 and PC2 each have a NIC. The PC1 binding has two ip:192.168.18.252 and 200.200.200.200. PC2 binding has a ip:200.200.200.4. The subnet masks for both PC1 and PC2 are 255.255.255.0. The default gateway for PC1 is: 192.168.28.254. The following code needs to be run on PC1.

Package mysocket;
Import java.net.*;
Public class moreconnection1 {    public static void main (String[]  args)     {        try          {             Inetaddress localaddress1 = inetaddress.getbyname ("200.200.200.200");             inetaddress localaddress2 =  inetaddress.getbyname ("192.168.18.252");             //  If you change LocalAddress1 to Localaddress2,socket1, you cannot connect successfully              socket socket1 = new socket ("200.200.200.4",  80, localaddress1,  0);             SYSTEM.OUT.PRINTLN ("Socket1 connection succeeded!");     &nBsp;       socket socket2 = new socket (" Www.ptpress.com.cn ",  80, localaddress2, 0);             SYSTEM.OUT.PRINTLN ("Socket2 connection succeeded!");             //  The following statement throws a IOException error              Socket socket3 = new  Socket ("www.ptpress.com.cn",  80, localaddress1, 0);             SYSTEM.OUT.PRINTLN ("Socket3 connection succeeded!");             socket1.close ();             socket2.close ();             socket3.close ();         }         catch  (exception e)         {             system.out.println (E.getmessage ());         }     }}

The output from running the above code is as follows:

SOCKET1 Connection Successful! Socket2 Connection Successful! Connection timed Out:connect

As can be seen from the above output, Socket1 and Socket2 are connected successfully, and Socket3 is not connected successfully. As can be seen from routine 4-8, Socket1 use LocalAddress1 to bind to 200.200.200.200 on connection, and PC2 IP is 200.200.200.4, so Socket1 uses IP and PC2 IP in the same network segment, so SOCKET1 can be connected successfully. If you change LocalAddress1 to LocalAddress2, Socket1 will not be able to connect successfully. An additional two socket connections Socket2 and Socket3 are connected via the Internet www.ptpress.com.cn. The difference is that Socket2 binds to 192.168.18.252, and Socket3 binds to 200.200.200.200. The result of their execution is that Socket2 can connect successfully and the Socket3 connection fails. This is because Socket2 binds the IP and PC1 's default gateway 192.168.18.254 on the same network segment, so Socket2 can connect to the Internet. The IP and PC1 IP that Socket3 binds to are not on the same network segment, so Socket3 will not be able to connect to the Internet.

Second, through Connect method to connect to the server

Not only can the socket class directly connect to the server through the construction method, but it can also establish an disconnected socket object and connect to the server via the Connect method. The Connect method of the socket class has two overloaded forms:

1. public void Connect (socketaddress endpoint) throws IOException

The Connect method of the socket class and its construction method have some differences in describing the server information (IP and port). In the Connect method , the IP and port are encapsulated in the subclass inetsocketaddress of the SocketAddress class, rather than as arguments in the constructor method as the host and integer ports in the form of a string. You can use this connect method as follows:

Socket socket = new socket (); Socket.connect (New Inetsocketaddress (host, port));

2. public void Connect (socketaddress endpoint, int timeout) throws IOException

This connect method is similar to the first connect, except for a timeout parameter. This parameter indicates the time-out of the connection , in milliseconds. With timeout set to 0, the default time-out is used.

When connecting to a server using the socket class's construction method, you can bind the IP directly through the construction method, and the Connect method can bind the IP by using the bind method of the socket class. Routine 4-9 demonstrates how to use the Connect method and the Bind method.

Package mysocket;
Import java.net.*;
Public class moreconnection2 { public static void main (String[] args)     {        try          {            socket socket1 =  new socket ();             socket socket2 = new  socket ();             socket socket3 = new  socket ();             socket1.connect (new  Inetsocketaddress ("200.200.200.4",  80));             socket1.close ();             SYSTEM.OUT.PRINTLN ("Socket1 connection succeeded!");                           /*                  Binding Socket2 to 192.168.18.252 will result in a IOException error                 socket2.bind (new inetsocketaddress ("192.168.18.252",  0));             */             socket2.bind (new inetsocketaddress ("200.200.200.200",  0));             socket2.connect (new  Inetsocketaddress ("200.200.200.4",  80));                            socket2.close ();             SYSTEM.OUT.PRINTLN ("Socket2 connection succeeded! ");
Socket3.bind (New Inetsocketaddress ("192.168.18.252", 0));                         Socket3.connect (New Inetsocketaddress ("200.200.200.4", 80), 2000);             Socket3.close ();         SYSTEM.OUT.PRINTLN ("Socket3 connection succeeded!");         } catch (Exception e) {System.out.println (E.getmessage ()); }     } }

The output of the above code is:

SOCKET1 Connection Successful! Socket2 Connection Successful! Connection timed Out:connect

The time-out period (2000 milliseconds) was set for the Socket3 to connect to the server in the code above, so Socket3 throws a IOException error in a very short time

Java network programming from getting started to mastering (14): A variety of ways to establish a network connection

Related Article

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.