📄 chapter15.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source:
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:Tjava14.rtf
Application Directory:c:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:02/04/2000
Translation Time:23:26:05
Translation Platform:Win32
Number of Output files:27
This File:Chapter15.html
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>15: Network programming</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
<a href="http://www.MindView.net">
<img src="mindview-head.gif" alt="MindView Inc." BORDER = "0"></a>
<CENTER>
<FONT FACE="Verdana" size = "-1">
[ <a href="README-HTML.txt">Viewing Hints</a> ]
[ <a href="http://www.mindview.net/TIJ2/index.html">2nd Edition</a> ]
[ <a href="http://www.mindview.net/MailingList.html">Free Newsletter</a> ] <br>
[ <a href="http://www.mindview.net/Training.html">Seminars</a> ]
[ <a href="http://www.mindview.net/javaCD2.html">Seminars on CD ROM</a> ]
[ <a href="http://www.mindview.net/CPPServices/#ConsultingServices">Consulting</a> ]
</FONT>
<H2><FONT FACE="Verdana">
Thinking in Java, 1st edition</FONT></H2>
<H3><FONT FACE="Verdana">©1998 by Bruce Eckel</FONT></H3>
<FONT FACE="Verdana" size = "-1">
[ <a href="Chapter14.html">Previous Chapter</a> ]
[ <a href="SimpleContents.html">Short TOC</a> ]
[ <a href="Contents.html">Table of Contents</a> ]
[ <a href="DocIndex.html">Index</a> ]
[ <a href="Chapter16.html">Next Chapter</a> ]
</FONT>
</CENTER>
</P></DIV><A NAME="Chapter_17"></A><A NAME="_Toc375545491"></A><A NAME="_Toc407441459"></A><A NAME="_Toc408018764"></A><A NAME="Heading510"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
15: Network programming</H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Verdana" SIZE=4>Historically,
<A NAME="Index2601"></A>network programming has been error-prone, difficult, and
complex.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The programmer had to know many
details about the network and sometimes even the hardware. You usually needed to
understand the various “layers” of the networking protocol, and
there were a lot of different functions in each different networking library
concerned with connecting, packing, and unpacking blocks of information;
shipping those blocks back and forth; and handshaking. It was a daunting
task.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">However, the concept of networking
is not so difficult. You want to get some information from that machine over
there and move it to this machine here, or vice versa. It’s quite similar
to reading and writing files, except that the file exists on a remote machine
and the remote machine can decide exactly what it wants to do about the
information you’re requesting or sending.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">One of Java’s great strengths
is painless networking. As much as possible, the underlying details of
networking have been abstracted away and taken care of within the JVM and local
machine installation of Java. The programming model you use is that of a file;
in fact, you actually wrap the network connection (a “socket”) with
stream objects, so you end up using the same method calls as you do with all
other streams. In addition, Java’s built-in multithreading is
exceptionally handy when dealing with another networking issue: handling
multiple connections at once.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">This chapter introduces
Java’s networking support using easy-to-understand
examples.</FONT><A NAME="_Toc375545492"></A><A NAME="_Toc408018765"></A><BR></P></DIV>
<A NAME="Heading511"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
Identifying a machine</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Of course, in order to tell one
machine from another and to make sure that you are connected with the machine
you want, there must be some way of uniquely <A NAME="Index2602"></A>identifying
machines on a network. Early networks were satisfied to provide unique names for
machines within the local network. However, Java works within the Internet,
which requires a way to uniquely identify a machine from all the others <I>in
the world</I>. This is accomplished with the
<A NAME="Index2603"></A><A NAME="Index2604"></A><A NAME="Index2605"></A>IP
(Internet Protocol) address that can exist in two forms:
<A NAME="Index2606"></A><A NAME="Index2607"></A><A NAME="Index2608"></A><A NAME="Index2609"></A></FONT><BR></P></DIV>
<OL>
<LI><FONT FACE="Georgia"> The familiar DNS (Domain Name Service) form. My
domain name is <B>bruceeckel.com</B>, so suppose I have a computer called
<B>Opus</B> in my domain. Its domain name would be <B>Opus.bruceeckel.com</B>.
This is exactly the kind of name that you use when you send email to people, and
is often incorporated into a World-Wide-Web
address.</FONT><LI><FONT FACE="Georgia"> Alternatively, you can use the
“dotted quad” form, which is four numbers separated by dots, such as
<B>123.255.28.120</B>.</FONT></OL><DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In
both cases, the IP address is represented internally as a 32-bit
number</FONT><A NAME="fnB59" HREF="#fn59">[59]</A><FONT FACE="Georgia">
(so each of the quad numbers cannot exceed 255), and you can get a special Java
object to represent this number from either of the forms above by using the
<B>static</B> <B>InetAddress.getByName( )</B> method that’s in
<B>java.net</B>. The result is an object of type <B>InetAddress</B> that you can
use to build a “socket” as you will see later.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">As a simple example of using
<B>InetAddress.getByName( )</B>, consider what happens if you have a
dial-up Internet service provider (ISP). Each time you dial up, you are assigned
a temporary IP address. But while you’re connected, your IP address has
the same validity as any other IP address on the Internet. If someone connects
to your machine using your IP address then they can connect to a Web server or
FTP server that you have running on your machine. Of course, they need to know
your IP address, and since it’s assigned each time you dial up, how can
you find out what it is?</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The following program uses
<B>InetAddress.getByName( )</B> to produce your IP address. To use it, you
must know the name of your computer. It has been tested only on Windows 95, but
there you can go to “Settings,” “Control Panel,”
“Network,” and then select the “Identification” tab.
“Computer name” is the name to put on the command
line.</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: WhoAmI.java</font>
<font color=#009900>// Finds out your network address when you're </font>
<font color=#009900>// connected to the Internet.</font>
<font color=#0000ff>package</font> c15;
<font color=#0000ff>import</font> java.net.*;
<font color=#0000ff>public</font> <font color=#0000ff>class</font> WhoAmI {
<font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args)
<font color=#0000ff>throws</font> Exception {
<font color=#0000ff>if</font>(args.length != 1) {
System.err.println(
<font color=#004488>"Usage: WhoAmI MachineName"</font>);
System.exit(1);
}
InetAddress a =
InetAddress.getByName(args[0]);
System.out.println(a);
}
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">In my case, the machine is called
“Colossus” (from the movie of the same name, because I keep putting
bigger disks on it). So, once I’ve connected to my ISP I run the
program:</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>java WhoAmI Colossus</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">I get back a message like this (of
course, the address is different each time):</FONT><BR></P></DIV>
<BLOCKQUOTE><FONT SIZE = "+1"><PRE>Colossus/199.190.87.75</PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">If I tell my friend this address,
he can log onto my personal Web server by going to the URL
<I>http://199.190.87.75</I> (only as long as I continue to stay connected during
that session). This can sometimes be a handy way to distribute information to
someone else or to test out a Web site configuration before posting it to a
“real”
server.</FONT><A NAME="_Toc375545493"></A><A NAME="_Toc408018766"></A><BR></P></DIV>
<A NAME="Heading512"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
Servers and clients</H3></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The whole point of a network is to
allow two machines to connect and talk to each other. Once the two machines have
found each other they can have a nice, two-way conversation. But how do they
find each other? It’s like getting lost in an amusement park: one machine
has to stay in one place and listen while the other machine says, “Hey,
where are you?”</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The machine that “stays in
one place” is called the
<A NAME="Index2610"></A><A NAME="Index2611"></A><I>server</I>, and the one that
seeks is called the
<A NAME="Index2612"></A><A NAME="Index2613"></A><I>client</I>. This distinction
is important only while the client is trying to connect to the server. Once
they’ve connected, it becomes a two-way communication process and it
doesn’t matter anymore that one happened to take the role of server and
the other happened to take the role of the client.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">So the job of the server is to
listen for a connection, and that’s performed by the special server object
that you create. The job of the client is to try to make a connection to a
server, and this is performed by the special client object you create. Once the
connection is made, you’ll see that at both server and client ends, the
connection is just magically turned into an IO stream object, and from then on
you can treat the connection as if you were reading from and writing to a file.
Thus, after the connection is made you will just use the familiar IO commands
from Chapter 10. This is one of the nice features of Java
networking.</FONT><BR></P></DIV>
<A NAME="Heading513"></A><FONT FACE = "Verdana"><H4 ALIGN="LEFT">
Testing programs without a network<BR><A NAME="Index2614"></A></H4></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">For many reasons, you might not
have a client machine, a server machine, and a network available to test your
programs. You might be performing exercises in a classroom situation, or you
could be writing programs that aren’t yet stable enough to put onto the
network. The creators of the Internet Protocol were aware of this issue, and
they created a special address called
<A NAME="Index2615"></A><A NAME="Index2616"></A><B>localhost</B> to be the
<A NAME="Index2617"></A><A NAME="Index2618"></A>“local loopback” IP
address for testing without a network. The generic way to produce this address
in Java is:</FONT><BR></P></DIV>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -