_chapter 3.htm
来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,237 行 · 第 1/4 页
HTM
1,237 行
and then disconnects.</p>
<h4 class="docSection2Title" id="ch03lev2sec4">Internet addresses</h4>
<p class="docText">Usually, you don't have to worry too much about Internet
addresses梩he numerical host addresses that consist of four bytes (or, with
IPv6, six bytes) such as 132.163.4.102. However, you can use the <tt>InetAddress</tt>
class if you need to convert between host names and Internet addresses.</p>
<p class="docText">As of SDK 1.4, the <tt>java.net</tt> package supports IPv6
Internet addresses, <span class="docEmphasis">provided the host operating system
does.</span> For example, you'll be able to make use of IPv6 addresses on
Solaris but, at the time of this writing, not on Windows.</p>
<p class="docText">The static <tt>getByName</tt> method returns an <tt>
InetAddress</tt> object of a host.</p>
<p class="docText">For example,</p>
<pre>InetAddress address
= InetAddress.getByName("time-A.timefreq.bldrdoc.gov");
</pre>
<p class="docText">returns an <tt>InetAddress</tt> object that encapsulates the
sequence of four bytes 132.163.4.102. You can access the bytes with the <tt>
getAddress</tt> method.</p>
<pre>byte[] addressBytes = address.getAddress();
</pre>
<p class="docText">Some host names with a lot of traffic correspond to multiple
Internet addresses, to facilitate load balancing. For example, at the time of
this writing, the host name
<a class="docLink" href="http://java.sun.com" target="_blank">java.sun.com</a>
corresponds to three different Internet addresses. One of them is picked at
random when the host is accessed. You can get all hosts with the <tt>
getAllByName</tt> method.</p>
<pre>InetAddress[] addresses = InetAddress.getAllByName(host);
</pre>
<p class="docText">Finally, you sometimes need the address of the local host. If
you simply ask for the address of <tt>localhost</tt>, you always get the address
127.0.0.1, which isn't very useful. Instead, use the static <tt>getLocalHost</tt>
method to get the address of your local host.</p>
<pre>InetAddress address
= InetAddress.getLocalHost();
</pre>
<p class="docText"><a class="docLink" href="#ch03list05">Example 3-5</a> is a
simple program that prints the Internet address of your local host if you do not
specify any command-line parameters, or all Internet addresses of another host
if you specify the host name on the command line, such as</p>
<pre>java InetAddressTest java.sun.com
</pre>
<h5 id="ch03list05" class="docExampleTitle">Example 3-5 InetAddressTest.java</h5>
<pre> 1. import java.net.*;
2.
3. /**
4. This program demonstrates the InetAddress class.
5. Supply a host name as command line argument, or run
6. without command line arguments to see the address of the
7. local host.
8. */
9. public class InetAddressTest
10. {
11. public static void main(String[] args)
12. {
13. try
14. {
15. if (args.length > 0)
16. {
17. String host = args[0];
18. InetAddress[] addresses
19. = InetAddress.getAllByName(host);
20. for (int i = 0; i < addresses.length; i++)
21. System.out.println(addresses[i]);
22. }
23. else
24. {
25. InetAddress localHostAddress
26. = InetAddress.getLocalHost();
27. System.out.println(localHostAddress);
28. }
29. }
30. catch (Exception e)
31. {
32. e.printStackTrace();
33. }
34. }
35. }
</pre>
<div class="docNote">
<p class="docNoteTitle">NOTE</p>
<table cellSpacing="0" cellPadding="1" width="90%" border="0">
<tr>
<td vAlign="top" width="60">
<img alt="graphics/note.gif" src="note.gif" align="left" border="0" width="54" height="53"><br>
</td>
<td vAlign="top">
<p class="docText">In this book, we cover only the TCP (Transmission
Control Protocol) networking protocol. TCP establishes a reliable
connection between two computers. The Java platform also supports the
so-called UDP (User Datagram Protocol) protocol, which can be used to send
packets (also called <span class="docEmphasis">datagrams</span>) with much
less overhead than that for TCP. The drawback is that the packets can be
delivered in random order, or even dropped altogether. It is up to the
recipient to put the packets in order and to request retransmission of
missing packets. UDP is most suited for applications where missing packets
can be tolerated, for example, in audio or video streams, or for
continuous measurements.</td>
</tr>
</table>
</div>
<h5 class="docSection3Title" id="ch03lev3sec2"><tt>java.net.Socket</tt></h5>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<ul>
<li>
<p class="docList"><tt>Socket(String host, int port)</tt></p>
<p class="docList">creates a socket and connects it to a port on a remote
host.</p>
<table cellSpacing="0" cellPadding="1" width="93%" border="1">
<colgroup span="3" align="left">
</colgroup>
<tr>
<td class="docTableCell" vAlign="top"><span class="docEmphasis">
Parameters:</span> </td>
<td class="docTableCell" vAlign="top"><tt>host</tt></td>
<td class="docTableCell" vAlign="top">the host name</td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>port</tt></td>
<td class="docTableCell" vAlign="top">the port number</td>
</tr>
</table>
<p> </li>
<li>
<p class="docList"><tt>Socket()</tt></p>
<p class="docList">creates a socket that has not yet been connected.</li>
<li>
<p class="docList"><tt>void connect(SocketAddress address)</tt></p>
<p class="docList">connects this socket to the given address. (Since SDK 1.4)</li>
<li>
<p class="docList"><tt>void connect(SocketAddress address, int timeout)</tt></p>
<p class="docList">connects this socket to the given address or returns if the
time interval expired. (Since SDK 1.4)</p>
<table cellSpacing="0" cellPadding="1" width="93%" border="1">
<colgroup span="3" align="left">
</colgroup>
<tr>
<td class="docTableCell" vAlign="top"><span class="docEmphasis">
Parameters:</span> </td>
<td class="docTableCell" vAlign="top"><tt>address</tt></td>
<td class="docTableCell" vAlign="top">the remote address</td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>timeout</tt></td>
<td class="docTableCell" vAlign="top">the timeout in milliseconds</td>
</tr>
</table>
<p> </li>
<li>
<p class="docList"><tt>boolean isConnected()</tt></p>
<p class="docList">returns <tt>true</tt> if the socket is connected. (Since
SDK 1.4)</li>
<li>
<p class="docList"><tt>void close()</tt></p>
<p class="docList">closes the socket.</li>
<li>
<p class="docList"><tt>boolean isClosed()</tt></p>
<p class="docList">returns <tt>true</tt> if the socket is closed. (Since SDK
1.4)</li>
<li>
<p class="docList"><tt>InputStream getInputStream()</tt></p>
<p class="docList">gets the input stream to read from the socket.</li>
<li>
<p class="docList"><tt>OutputStream getOutputStream()</tt></p>
<p class="docList">gets an output stream to write to this socket.</li>
<li>
<p class="docList"><tt>void setSoTimeout(int timeout)</tt></p>
<p class="docList">sets the blocking time for read requests on this <tt>Socket</tt>.
If the timeout is reached, then an <tt>InterruptedIOException</tt> is raised.</p>
<table cellSpacing="0" cellPadding="1" width="93%" border="1">
<colgroup span="3" align="left">
</colgroup>
<tr>
<td class="docTableCell" vAlign="top"><span class="docEmphasis">
Parameters:</span></td>
<td class="docTableCell" vAlign="top"><tt>timeout</tt></td>
<td class="docTableCell" vAlign="top">the timeout in milliseconds (0 for
infinite timeout)</td>
</tr>
</table>
<p> </li>
<li>
<p class="docList"><tt>void shutdownOutput()</tt></p>
<p class="docList">sets the output stream to "end of stream."</li>
<li>
<p class="docList"><tt>void shutdownInput()</tt></p>
<p class="docList">sets the input stream to "end of stream."</li>
<li>
<p class="docList"><tt>boolean isOutputShutdown</tt></p>
<p class="docList">returns <tt>true</tt> if output has been shut down. (Since
SDK 1.4)</li>
<li>
<p class="docList"><tt>boolean isInputShutdown</tt></p>
<p class="docList">returns <tt>true</tt> if input has been shut down.(Since
SDK 1.4)</li>
</ul>
<h5 class="docSection3Title" id="ch03lev3sec3"><tt>java.net.InetAddress</tt></h5>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<ul>
<li>
<p class="docList"><tt>static InetAddress getByName(String host)</tt></li>
<li>
<p class="docList"><tt>static InetAddress[] getAllByName(String host)</tt></p>
<p class="docList">These methods construct an <tt>InetAddress</tt>, or an
array of all Internet addresses, for the given host name.</li>
<li>
<p class="docList"><tt>static InetAddress getLocalHost()</tt></p>
<p class="docList">constructs an <tt>InetAddress</tt> for the local host.</li>
<li>
<p class="docList"><tt>byte[] getAddress()</tt></p>
<p class="docList">returns an array of bytes that contains the numerical
address.</li>
<li>
<p class="docList"><tt>String getHostAddress()</tt></p>
<p class="docList">returns a string with decimal numbers, separated by
periods, for example <tt>"132.163.4.102"</tt>.</li>
<li>
<p class="docList"><tt>String getHostName()</tt></p>
<p class="docList">returns the host name.</li>
</ul>
<h5 class="docSection3Title" id="ch03lev3sec4"><tt>java.net.InetSocketAddress</tt></h5>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<p class="docText">Since SDK 1.4:</p>
<ul>
<li>
<p class="docList"><tt>InetSocketAddress(String hostname, int port)</tt></p>
<p class="docList">constructs an address object with the given host and port,
resolving the host name during construction. If the host name cannot be
resolved, then the address object's <tt>unresolved</tt> property is set to <tt>
true</tt>.</li>
<li>
<p class="docList"><tt>boolean isUnresolved()</tt></p>
<p class="docList">returns <tt>true</tt> if this address object could not be
resolved.</li>
</ul>
<h3 class="docSection1Title" id="c3s5">URL Connections</h3>
<p class="docText">In the last section, you saw how to use socket-level
programming to connect to an SMTP server and send an e-mail message. It is nice
to know that this can be done, and to get a glimpse of what goes on "under the
hood" of an Internet service such as e-mail. However, if you are planning an
application that incorporates e-mail, you will probably want to work at a higher
level and use a library that encapsulates the protocol details. For example, Sun
Microsystems has developed the JavaMail API as a standard extension of the Java
platform. In the JavaMail API, you simply issue a call such as</p>
<pre>Transport.send(message);
</pre>
<p class="docText">to send a message. The library takes care of message
protocols, multiple recipients, handling attachments, and so on.</p>
<p class="docText">For the remainder of this chapter, we will concentrate on
higher-level services that the standard edition of the Java platform provides.
Of course, the runtime library uses sockets to implement these services. But you
don't have to worry about the protocol details when you use the higher-level
services.</p>
<h4 class="docSection2Title" id="ch03lev2sec5">URLs and URIs</h4>
<p class="docText">The <tt>URL</tt> and <tt>URLConnection</tt> classes
encapsulate much of the complexity of retrieving information from a remote site.
Here is how you specify a URL.</p>
<pre>URL url = new URL(urlString);
</pre>
<p class="docText">The Java 2 platform supports both HTTP and FTP resources.</p>
<p class="docText">If you simply want to fetch the contents of the resource,
then you can use the <tt>openStream</tt> method of the <tt>URL</tt> class. This
method yields an <tt>InputStream</tt> object. Using this stream object, you can
easily read the contents of the resource.</p>
<pre>InputStream uin = <span class="docEmphStrong">url.openStream();</span>
BufferedReader in
= new BufferedReader(new InputStreamReader(uin));
String line;
while ((line = in.readLine()) != null)
{
<span class="docEmphasis">process</span> line;
}
</pre>
<p class="docText">As of SDK 1.4, the <tt>java.net</tt> package makes a useful
distinction between URLs (uniform resource <span class="docEmphasis">locators</span>)
and URIs (uniform resource <span class="docEmphasis">identifiers</span>).</p>
<p class="docText">A URI is a purely syntactical construct that specifies the
various parts of the string specifying a web resource. A URL is a special kind
of URI, namely one with sufficient information to <span class="docEmphasis">
locate</span> a resource. Other URIs, such as</p>
<pre>mailto:cay@horstmann.com
</pre>
<p class="docText">are not locators梩here is no data to locate from this
identifier. Such a URI is called a URN (uniform resource
<span class="docEmphasis">name</span>).</p>
<p class="docText">In the Java library, the <tt>URI</tt> class has no methods
for accessing the resource that the identifier specifies梚ts sole purpose is
parsing. In contrast, the <tt>URL</tt> class can open a stream to the resource.
For that reason, the <tt>URL</tt> class only works with identifiers of a kind
that the Java library knows how to handle, such as an HTTP or FTP URL.</p>
<p class="docText">To see why a URI class is necessary, consider how complex
URLs can be. For example,</p>
<pre>http://maps.yahoo.com/py/maps.py?csz=Cupertino+CA
ftp://username:password@ftp.yourserver.com/pub/file.txt
</pre>
<p class="docText">The URI specification gives rules for the makeup of these
identifiers. A URI has the syntax</p>
<pre>[<span class="docEmphasis">scheme</span>:]<span class="docEmphasis">schemeSpecificPart</span>[#<span class="docEmphasis">fragment</span>]
</pre>
<p class="docText">Here, the [
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?