In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail the ways to connect to the database in Java network programming, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
First, connect the server through the construction method
We can connect to the server in different ways through six overloaded constructors. These six overloaded constructors can be divided into two categories:
1. Automatically select IP
This method is the most commonly used. The so-called automatic selection of IP means that when the machine has multiple network cards or binds multiple IP on one network card, the socket class will automatically select an available IP for us. Four of the above six constructors use this method to connect to the server.
(1) public Socket (String host, int port)
This is the most commonly used construction method, which is used in the previous example. When using it, you only need to provide a string type IP or domain name and an integer port number. Two errors may be thrown in this constructor: UnknownHostException and IOException. The reason for the * * error is that the host we provided does not exist or is illegal, while 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 * *, except that the host in string form is changed to the InetAddress object type. The InetAddress class is used in this constructor mainly because it is more efficient to use the InetAddress class because you may need to use the Socket class to connect to the same IP or domain name multiple times in the program. In addition, when using a string type of host to connect to the server, two errors may occur, but using the InetAddress object to describe host, only IOException errors will occur, this is because when you pass the IP or domain name to InetAddress, InetAddress will automatically check the IP or domain name, if the IP or domain name is invalid, then InetAddress will throw a UnknownHostException error, not by the constructor of the Socket class. 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 construction method is similar to * * construction methods, except that there is an extra stream parameter of type boolean. If the stream is true, then the construction method is exactly the same as the * construction method. If stream is false, use the UDP protocol to establish a UDP connection (UDP will be discussed in detail in the following sections, as long as you know that the difference between it and TCP*** is that UDP is connectionless and TCP is connectionless), maybe it is because the developers of Sun did not consider writing DatagramSocket classes that handle UDP connections when writing Socket classes, so they added the function of establishing UDP connections to Socket classes. However, Sun added the DatagramSocket class to later JDK, so this constructor is useless, so Sun sets it to the Deprecated tag, that is, this constructor can be deleted in future versions of JDK. For the above reasons, when using Java to write network programs, try not to use this construction method to establish UDP connections.
(4) public Socket (InetAddress inetaddress, int port, boolean flag)
This constructor, like the flag tag of the third constructor, is not recommended.
The following code demonstrates the use of the above four 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 a domain name that does not exist, a UnknownHostException error will be thrown / / Test public Socket (String host, int port) socket1 = new Socket ("www.ptpress.com.cn", 80); System.out.println ("socket1 connected successfully!") / / 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 to use / / 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 thrown!") } catch (IOException e) {System.out.println ("IOException thrown!");} finally {closeSocket (socket1); closeSocket (socket2); closeSocket (socket3); closeSocket (socket4);}
The * * in the above code closes the open Socket connection through finally, which is a good habit. Because the code that closes the Socket connection is executed only if it is written in finally, regardless of whether there is an error or not. Note, however, that before closing a Socket connection, you must check whether the Socket object is null, because the error is likely to occur when the connection is established, so the Socket object is not established successfully and does not need to be closed.
two。 Bind IP manually
When there are multiple IP on the machine (these IP may be on multiple network cards or multiple IP bound to a network card), it is up to the client to determine which IP to use when connecting to the server. This must be handled using the other two constructors of the Socket class. Let's take a look at how these two constructors use a specific IP 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, and the * * section is the first two parameters: host and port, which represent the IP and port number of the server to connect to, respectively. The second part is the last two parameters: inetaddress and localPort. Where inetaddress represents the local IP to be used, and localPort represents the local port number to bind. This localPort this is set to any unbound port number of the machine. If you set the value of localPort to 0Magnejava, an unbound port number will be selected between 1024 and 65535. Therefore, localPort is set to 0 in general.
Public Socket (InetAddress inetaddress, int port, InetAddress inetaddress1, int localPort)
This construction method is basically the same as the * construction method, except that the * parameter host is replaced with inetaddress. Other methods of use are similar to * construction methods.
These two constructors will be used to do an experiment in the following code. Let's assume that there are two computers: PC1 and PC2. PC1 and PC2 each have a network card. The PC1 binding has two IP:192.168.18.252 and 200.200.200.200. The PC2 binding has an IP:200.200.200.4. The subnet mask for both PC1 and PC2 is 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 changing localAddress1 to localAddress2,socket1 fails to connect successfully Socket socket1 = new Socket ("200.200.200.200.4", 80, localAddress1, 0); System.out.println ("socket1 connection succeeded!"); Socket socket2 = new Socket ("www.ptpress.com.cn", 80, localAddress2, 0); System.out.println ("socket2 connection succeeded!") / / the following statement throws an 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 succeeded!
Socket2 connection succeeded!
Connection timed out: connect
As you can see from the output above, socket1 and socket2 have been connected successfully, while socket3 has not. As you can see from routines 4-8, socket1 is bound to 200.200.200.200 when connecting using localAddress1, while the IP of PC2 is 200.200.200.4, so the IP used by socket1 and the IP of PC2 are on the same network segment, so the socket1 can be connected successfully. If you change localAddress1 to localAddress2, socket1 will not be able to connect successfully. The other two Socket connections socket2 and socket3 are connected to www.ptpress.com.cn through Internet. The difference is that socket2 binds 192.168.18.252, while socket3 binds 200.200.200.200. The result of their execution is that the socket2 can connect successfully, while the socket3 connection fails. This is because the IP bound by socket2 and the default gateway of PC1, 192.168.18.254, are on the same network segment, so socket2 can connect to Internet. The IP bound by socket3 and the IP of PC1 are not on the same network segment, so socket3 will not be able to connect to Internet.
Second, connect to the server through connect method
The Socket class can not only connect to the server directly through constructors, but also establish unconnected Socket objects and connect to the server through the connect method. The connect method of the Socket class has two overloaded forms:
1. Public void connect (SocketAddress endpoint) throws IOException
There are some differences between the connect method of the Socket class and its constructor in describing the server information (IP and port). Instead of using host in string form and port in integer form as parameters in the connect method, the IP and port are directly encapsulated in InetSocketAddress, a subclass of the SocketAddress class. 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 * connect, except that it has an extra timeout parameter. This parameter represents the timeout of the connection, in milliseconds. If timeout is set to 0, the default timeout is used.
When you connect to the server using the constructor of the Socket class, you can bind the local IP directly through the constructor, while the connect method can bind the local IP through the bind method of the Socket class. Routines 4-9 demonstrate how to use the connect and bind methods.
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 an 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 succeeded!
Socket2 connection succeeded!
Connection timed out: connect
The socket3 in the above code sets a timeout (2000 milliseconds) for connecting to the server, so socket3 throws an IOException error in a very short time.
Java network programming on the way to connect to the database which is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.