Anda di halaman 1dari 24

Networking

Java is the premier language for network programming are the classes
defned in the java.net package. They provide an easy-to-use means by
which programmers of all skill levels can access network resources.
Networking Basics
At the core of Javas networking support is the concept of a socket.
A socket identifes an endpoint in a network.
The socket paradigm was part of the 4.!"# !erkeley $%&' release
in the early ()*+s. !ecause of this, the term Berkeley socket is also
used.
"ockets are at the foundation of modern networking because a
socket allows a single computer to serve many di-erent clients at
once, as well as to serve many di-erent types of information.
This is accomplished through the use of a port, which is a
numbered socket on a particular machine.
A server process is said to .listen/ to a port until a client connects to
it.
A server is allowed to accept multiple clients connected to the same
port number, although each session is uni0ue.
To manage multiple client connections, a server process must be
multithreaded or have some other means of multiple1ing the
simultaneous &23.
"ocket communication takes place via a protocol.
Internet Protocol (IP) is a low-level routing protocol that breaks data
into small packets and sends them to an address across a network,
which does not guarantee to deliver said packets to the destination.
Transmission Control Protocol 4T567 is a higher-level protocol that
manages to robustly string together these packets, sorting and
retransmitting them as necessary to reliably transmit data.
A third protocol, User Datagram Protocol (UDP), sits ne1t to T56 and
can be used directly to support fast, connectionless, unreliable
transport of packets.
3nce a connection has been established, a higher-level protocol
ensues, which is dependent on which port you are using. T562&6
reserves the lower (,+4 ports for specifc protocols. 8any of these
will seem familiar to you if you have spent any time surfng the
&nternet. 6ort number ( is for 9T6: ; is for Telnet: < is for e-mail:
4; is for whois: =) is for fnger: *+ is for >TT6: (() is for net news?
and the list goes on. &t is up to each protocol todetermine how a
client should interact with the port.
9or e1ample, >TT6 is the protocol that web browsers and servers
use to transfer hyperte1t pages and images. &t is a 0uite simple
protocol for a basic page-browsing web server. >eres how it works.
@hen a client re0uests a fle from an >TT6 server, an actionknown
as a hit, it simply sends the name of the fle in a special format to a
predefned portand reads back the contents of the fle. The server
also responds with a status code to tell theclient whether or not the
re0uest can be fulflled and why.
A key component of the &nternet is the address. Avery computer on
the &nternet has one.
An &nternet address is a number that uni0uely identifes each
computer on the %et. 3riginally, all &nternet addresses consisted of
;-bit values, organiBed as four *-bit values. This address type was
specifed by &6v4 4&nternet 6rotocol, version 47.
>owever, a new addressing scheme, called &6vC 4&nternet 6rotocol,
version C7 has come into play. &6vC uses a (*-bit value to represent
an address, organiBed into eight (C-bit chunks. Although there are
several reasons for and advantages to &6vC, the main one is that it
supports a much larger address space than does &6v4.
To provide backward compatibility with &6v4, the low-order ; bits of
an &6vC address can contain a valid &6v4 address. Thus, &6v4 is
upwardly compatible with &6vC.
9ortunately, when using Java, you wont normally need to worry
about whether &6v4 or &6vC addresses are used because Java
handles the details for you. Just as the numbers of an &6 address
describe a network hierarchy, the name of an &nternet address,
called its domain name, describes a machines location in a name
space.
9or e1ample, www.osborne.com is in the COM domain 4reserved
for $.". commercial sites7: it is called osorne 4after the company
name7, and !!! identifes the server for web re0uests.
An &nternet domain name is mapped to an &6 address by the
Domain "aming #er$ice (D"#). This enables users to work with
domain names, but the &nternet operates on &6 addresses.
The %etworking 5lasses and &nterfaces
Java supports both the T56 and $#6 protocol families.
T56 is used for reliable stream-based &23 across the network.
$#6 supports a simpler, hence faster, point-to-point datagram-
oriented model.
The classes contained in the java.net package are shown hereD
Authenticator
&netCAddress
"erver"ocket
5acheEe0uest
&netAddress
"ocket
5acheEesponse
&net"ocketAddress
"ocketAddress
5ontent>andler
&nterfaceAddress
"ocket&mpl
5ookie>andler
Jar$EF5onnection
"ocket6ermission
5ookie8anager
8ulticast"ocket
$E&
#atagram6acket
%et6ermission
$EF
#atagram"ocket
%etwork&nterface
$EF5lassFoader
#atagram"ocket&mpl
6asswordAuthentication
$EF5onnection
>ttp5ookie
6ro1y
$EF#ecoder
>ttp$EF5onnection
6ro1y"elector
$EFAncoder
&#%
Eesponse5ache
$EF"tream>andler
&net4Address
"ecure5acheEesponse
The java.net packages interfaces are listed hereD
5ontent>andler9actory
#atagram"ocket&mpl9actory
"ocket3ptions
5ookie6olicy 4Added by Java "A C.7
9ile%ame8ap
$EF"tream>andler9actory
5ookie"tore 4Added by Java "A C.7
"ocket&mpl9actory
InetAddress
The InetAddress class is used to encapsulate both the numerical &6
address and the domain name for that address.
Gou interact with this class by using the name of an &6 host, which is
more convenient and understandable than its &6 address.
The InetAddress class hides the number inside. InetAddress can
handle both &6v4 and &6vC addresses.
Factory Methods
The InetAddress class has no visible constructors.
To create an InetAddress obHect, you have to use one of the
available factory methods.
%actory methods are merely a convention whereby static methods in
a class return an instance of that class.
This is done in lieu of overloading a constructor with various
parameter lists when having uni0ue method names makes the
results much clearer. Three commonly used InetAddress factory
methods are shown hereD
static &netAddress getFocal>ost4 7throws $nknown>ostA1ception
static &netAddress get!y%ame4"tring host"ame7throws
$nknown>ostA1ception
static &netAddressI J getAll!y%ame4"tring host"ame7throws
$nknown>ostA1ception
The getLocalHost( method simply returns the InetAddress
obHect that represents the localhost.
The getByName( method returns an InetAddress for a host
name passed to it. &f these methods are unable to resolve the host
name, they throw an !nknownHost"#ce$tion. 3n the &nternet, it
is common for a single name to be used to represent several
machines. &n the world of web servers, this is one way to provide
some degree of scaling.
The getAllByName( factory method returns an array of
InetAddresses that represent all of the addresses that a particular
name resolves to. &t will also throw an !nknownHost"#ce$tion if it
cant resolve the name to at least one address.
InetAddress also includes the factory method getByAddress( ,
which takes an &6 address and returns an InetAddress obHect.
Aither an &6v4 or an &6vC address can be used.
The following e1ample prints the addresses and names of the local
machine and two well-known &nternet web sitesD
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws
UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("osborne.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
>ere is the output produced by this program. 43f course, the output you
see may be
slightly di-erent.7
default/206.148.209.138
osborne.com/198.45.24.162
www.nba.com/64.5.96.214
www.nba.com/64.5.96.216
Instance Methods
The InetAddress class has several other methods, which can be used on
the obHects returned by the methods Hust discussed. >ere are some of the
more commonly used methodsD
boolean e0uals43bHect other7 %% Eeturns true if this obHect has the same
&nternet address as other.
byteI J getAddress4 7 %% Eeturns a byte array that represents the obHects
&6 address in network byte order.
"tring get>ostAddress4 7 %% Eeturns a string that represents the host
address associated with the &netAddress obHect.
"tring get>ost%ame4 7 %% Eeturns a string that represents the host name
associated with the &netAddress obHect.
boolean is8ulticastAddress4 7 %% Eeturns true if this address is a multicast
address. 3therwise,it returns false.
"tring to"tring4 7 %% Eeturns a string that lists the host name and the &6
address for
convenience.
Inetv&Address and Inetv'Address
!eginning with version (.4, Java has included support for &6vC
addresses. !ecause of this, two subclasses of InetAddress were
createdD Inet&Address and Inet'Address.
Inet&Address represents a traditional-style &6v4 address.
Inet'Address encapsulates a new-style &6vC address.
!ecause they are subclasses of InetAddress, an InetAddress
reference can refer to either.
An &nternet address is a number that uni0uely identifes each
computer on the %et. 3riginally, all &nternet addresses consisted of
;-bit values, organiBed as four *-bit values. This address type was
specifed by &6v4 4&nternet 6rotocol, version 47.
>owever, a new addressing scheme, called &6vC 4&nternet 6rotocol,
version C7 has come into play. &6vC uses a (*-bit value to represent
an address, organiBed into eight (C-bit chunks. Although there are
several reasons for and advantages to &6vC, the main one is that it
supports a much larger address space than does &6v4.
()*+I* ,ockets
T562&6 sockets are used to implement reliable, bidirectional,
persistent, point-to-point, stream-based connections between hosts
on the &nternet.
A socket can be used to connect Javas &23 system to other
programs that may reside either on the local machine or on any
other machine on the &nternet.
There are two kinds of T56 sockets in Java. 3ne is for servers, and
the other is for clients.
The ,ocket class is for clients. &t is designed to connect to server
sockets and initiate protocol e1changes.
The ,erver,ocket class is designed to be a .listener,/ which waits
for clients to connect before doing anything.Thus, ,erver,ocket is
for servers.
()*+I* )lient ,ockets
The ,ocket class is for clients. &t is designed to connect to server
sockets and initiate protocol e1changes. !ecause client sockets are
the most commonly used by Java applications, they are e1amined
here.
The creation of a ,ocket obHect implicitly establishes a connection
between the client and server.

There are no methods or constructors that e1plicitly e1pose the
details of Astablishing that connection.
>ere are two constructors used to create client socketsD
"ocket4"tring host%ame, int port7
throws$nknown>ostA1ception,&3A1ception
5reates a socket connected to the named host and port.
"ocket4&netAddress ipAddress, int port7throws &3A1ception
5reates a socket using a pre-e1isting &netAddress obHect and a port.
,ocket defnes several instance methods. 9or e1ample, a ,ocket
can be e1amined at any time for the address and port information
associated with it, by use of the following methodsD
&netAddress get&netAddress4 7 %% Eeturns the &netAddress associated with
the "ocket
obHect. &t returns null if the socket is not connected.
int get6ort4 7 %% Eeturns the remote port to which the invoking "ocket
obHect is connected. &t returns + if the socket is not connected.
int getFocal6ort4 7 %% Eeturns the local port to which the invoking "ocket
obHect is bound. &t returns K( if the socket is not bound.
Gou can gain access to the input and output streams associated with
a ,ocket by use of the getIn$-t,tream( and
get.-$t-t,tream( methods, as shown here. Aach can throw an
I."#ce$tion if the socket has been invalidated by a loss of
connection. These streams are used e1actly like the &23 streams
described to send and receive data.
&nput"tream get&nput"tream4 7 throws &3A1ception
Eeturns the &nput"tream associated with the invoking socket.
3utput"tream get3utput"tream4 7throws &3A1ception
Eeturns the 3utput"tream associated with the invoking socket.
"everal other methods are available, including connect( , which
allows you to specify a new connection: is)onnected( , which
returns true if the socket is connected to a server:
isBo-nd( , which returns true if the socket is bound to an address:
and
is)losed( , which returns true if the socket is closed.
The following program provides a simple ,ocket e1ample. &t opens
a connection to a .whois/ port 4port 4;7 on the &nter%&5 server,
sends the command-line argument down the socket, and then prints
the data that is returned. &nter%&5 will try to look up the argument
as a registered &nternet domain name, and then send back the &6
address and contact information for that site.
// Demonstrate Sockets.
import java.net.*;
import java.io.*;
class Whois {
public static void main(String args[]) throws Exception
{
int c;
// Create a socket connected to internic.net, port 43.
Socket s = new Socket("internic.net", 43);
// Obtain input and output streams.
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "osborne.com" : args[0]) +
"\n";
// Convert to bytes.
byte buf[] = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((c = in.read()) != -1)
{
System.out.print((char) c);
}
s.close();
}
}
&f, for e1ample, you obtained information about osborne.com, youd get
something similar to the followingD
Whois Server Version 1.3
Domain names in the .com, .net, and .org domains can now be
registered
with many different competing registrars. Go to
http://www.internic.net
for detailed information.
Domain Name: OSBORNE.COM
Registrar: NETWORK SOLUTIONS, INC.
Whois Server: whois.networksolutions.com
Referral URL: http://www.networksolutions.com
Name Server: NS1.EPPG.COM
Name Server: NS2.EPPG.COM
.
.
.
!/L
The preceding e1ample was rather obscure because the modern
&nternet is not about the older protocols such as whois, fnger, and
9T6. &t is about @@@, the @orld @ide @eb.
The @eb is a loose collection of higher-level protocols and fle
formats, all unifed in a web browser. 3ne of the most important
aspects of the @eb is that Tim !erners-Fee devised a scaleable way
to locate all of the resources of the %et. 3nce you can reliably name
anything and everything, it becomes a very powerful paradigm. The
$niform Eesource Focator 4$EF7 does e1actly that.
The $EF provides a reasonably intelligible form to uni0uely identify
or address
information on the &nternet. $EFs are ubi0uitous: every browser uses them
to identify
information on the @eb. @ithin Javas network class library, the !/L class
provides a simple, concise A6& to access information across the &nternet
using $EFs.
All $EFs share the same basic format, although some variation is
allowed. >ere are two e1amplesD
htt$%++www.osborne.com+ and
htt$%++www.osborne.com%01+inde#.htm.
A $EF specifcation is based on four components. The frst is the
protocol to use, separated from the rest of the locator by a colon 4D7.
5ommon protocols are >TT6, 9T6, gopher, and fle, although these
days almost everything is being done via >TT6 4in fact, most
browsers will proceed correctly if you leave o- the .httpD22/ from
your $EF specifcation7.
The second component is the host name or &6 address of the host to
use: this is delimited on the left by double slashes 4227 and on the
right by a slash 427 or optionally a colon 4D7.
The third component, the port number, is an optional parameter,
delimited on the left from the host name by a colon 4D7 and on the
right by a slash 427. 4&t defaults to port *+, the predefned >TT6 port:
thus, .D*+/ is redundant.7
The fourth part is the actual fle path. 8ost >TT6 servers will
append a fle named inde#.html or inde#.htm to $EFs that refer
directly to a directory resource. Thus, htt$%++www.osborne.com+ is
the same as htt$%++www.osborne.com+inde#.htm.
Javas !/L class has several constructors: each can throw a
Mal2ormed!/L"#ce$tion.
3ne commonly used form specifes the $EF with a string that is identical
to what you see displayed in a browserD
$EF4"tring &rl#peci'er7 throws 8alformed$EFA1ception
The ne1t two forms of the constructor allow you to break up the $EF into
its component partsD
$EF4"tring protocol"ame, "tring host"ame, int port, "tring path7
throws 8alformed$EFA1ception
$EF4"tring protocol"ame, "tring host"ame, "tring path7
throws 8alformed$EFA1ception
Another fre0uently used constructor allows you to use an e1isting
$EF as a reference conte1t and then create a new $EF from that
conte1t. Although this sounds a little contorted, its really 0uite easy
and useful.
$EF4$EF &rlO(, "tring &rl#peci'er7 throws 8alformed$EFA1ception
The following e1ample creates a $EF to 3sbornes download page
and then e1amines
its propertiesD
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String args[]) throws
MalformedURLException {
URL hp = new URL("http://www.osborne.com/downloads");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
@hen you run this, you will get the following outputD
Protocol: http
Port: -1
Host: www.osborne
File: /downloads
Ext:http://www.osborne/downloads
%otice that the port is K(: this means that a port was not e1plicitly set.
Liven a !/L obHect,you can retrieve the data associated with it. To access
the actual bits or content information of a !/L, create a !/L)onnection
obHect from it, using its o$en)onnection( method, like thisD
urlc = url.openConnection()
o$en)onnection( has the following general formD
$EF5onnection open5onnection4 7 throws &3A1ception
&t returns a !/L)onnection obHect associated with the invoking !/L
obHect. %otice that it may throw an I."#ce$tion.
!/L)onnection
!/L)onnection is a general-purpose class for accessing the
attributes of a remote resource.
3nce you make a connection to a remote server, you can use
!/L)onnection to inspect the properties of the remote obHect
before actually transporting it locally.
These attributes are e1posed by the >TT6 protocol specifcation and,
as such, only make sense for !/L obHects that are using the >TT6
protocol.
!/L)onnection defnes several methods. >ere is a samplingD
int get5ontentFength4 7 %% Eeturns the siBe in bytes of the content
associated
with the resource. &f the length is unavailable, K( is returned.
"tring get5ontentType4 7 %% Eeturns the type of content found in the
resource.
This is the value of the content-type header feld. Eeturns null if the
content type is not available.
long get#ate4 7 %% Eeturns the time and date of the response
represented in terms of milliseconds since January (, ()=+ L8T.
long getA1piration4 7 %%Eeturns the e1piration time and date of the
resource represented in terms of milliseconds since January (, ()=+ L8T.
Mero is returned if the e1piration date is unavailable.
"tring get>eader9ield4int id17 %% Eeturns the value of the header feld at
inde1 id1.
4>eader feld inde1es begin at +.7 %%Eeturns null if the value of id1 e1ceeds
the number of felds.
"tring get>eader9ield4"tring feld%ame7 %%Eeturns the value of header
feld whose name is specifed by feld%ame. Eeturns null if the specifed
name is not found.
"tring get>eader9ieldNey4int id17 %% Eeturns the header feld key at inde1
id1. 4>eaderfeld inde1es begin at +.7 Eeturns null if the value of id1
e1ceeds the number of felds. 8apO"tring, FistO"tringPP
get>eader9ields4 7 %% Eeturns a map that contains all of the header felds
and values.
long getFast8odifed4 7 %% Eeturns the time and date, represented in terms
of milliseconds since January (, ()=+ L8T, of the last modifcation of the
resource. Mero is returnedif the last-modifed date is unavailable.
&nput"tream get&nput"tream4 7throws &3A1ception
Eeturns an &nput"tream that is linked to the resource. This stream can be
used to obtain the content of the resource.
%otice that !/L)onnection defnes several methods that handle
header information.
A header consists of pairs of keys and values represented as
strings. !y using getHeaderField( ,
you can obtain the value associated with a header key. !y calling
getHeaderFields( ,
you can obtain a map that contains all of the headers. "everal
standard header felds are available directly through methods such
as get3ate( and get)ontent(y$e( .
The following e1ample creates a !/L)onnection using the
o$en)onnection( method of a !/L obHect and then uses it to
e1amine the documents properties and contentD
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();
// get date
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " + hpCon.getContentType());
// get expiration date
d = hpCon.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
// get last-modified date
d = hpCon.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
int len = hpCon.getContentLength();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1)) { // && (--i > 0)) {
System.out.print((char) c);
}
input.close();
} else {
System.out.println("No content available.");
}
}
}
The program establishes an >TT6 connection to www.internic.net over
port *+. &t then displays several header values and retrieves the content.
>ere are the frst lines of the output 4the precise output will vary over
time7.
Date: Thu Jun 08 14:41:35 CDT 2006
Content-Type: text/html
No expiration information.
Last-Modified: Wed Oct 05 19:49:29 CDT 2005
Content-Length: 4917
=== Content ===
<html>
<head>
<title>InterNIC | The Internet's Network Information
Center</title>
<meta name="keywords"
content="internic,network information, domain registration">
<style type="text/css">
<!--
p, li, td, ul { font-family: Arial, Helvetica, sans-serif}
-->
</style>
</head>
Htt$!/L)onnection
Java provides a subclass of !/L)onnection that provides support
for >TT6 connections.
This class is called Htt$!/L)onnection. Gou obtain an
Htt$!/L)onnection in the same way Hust shown, by calling
o$en)onnection( on a !/L obHect, but you must cast the result
to Htt$!/L)onnection.
3nce you have obtained a reference to an Htt$!/L)onnection
obHect,
you can use any of the methods inherited from !/L)onnection.
Gou can also use any of the several methods defned by
Htt$!/L)onnection. >ere is a samplingD
static boolean get9ollowEedirects4 7 %% Eeturns true if redirects are
automatically followed and false otherwise. This feature is on by default.
"tring getEe0uest8ethod4 7 %% Eeturns a string representing how $EF
re0uests are
made. The default is LAT. 3ther options, such as 63"T,are available.
int getEesponse5ode4 7throws &3A1ception
Eeturns the >TT6 response code. K( is returned if noresponse code can be
obtained. An &3A1ception is thrown if the connection fails.
"tring getEesponse8essage4 7 throws &3A1ception
Eeturns the response message associated with the response code. Eeturns
null if no message is available. An &3A1ception is thrown if the connection
fails.
static void set9ollowEedirects4boolean how7
&f how is true, then redirects are automatically followed.
&f how is false, redirects are not automatically followed.
!y default, redirects are automatically followed.
void setEe0uest8ethod4"tring how7 throws 6rotocolA1ception
"ets the method by which >TT6 re0uests are made to that specifed by
how. The default method is LAT, but other options, such as 63"T, are
available. &f how is
invalid, a 6rotocolA1ception is thrown.
The following program demonstrates Htt$!/L)onnection. &t frst
establishes aconnection to www.google.com. Then it displays the
re0uest method, the response code,and the response message.
9inally, it displays the keys and values in the response header.
// Demonstrate HttpURLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLDemo
{
public static void main(String args[]) throws Exception {
URL hp = new URL("http://www.google.com");
HttpURLConnection hpCon = (HttpURLConnection)
hp.openConnection();
// Display request method.
System.out.println("Request method is " +
hpCon.getRequestMethod());
// Display response code.
System.out.println("Response code is " +
hpCon.getResponseCode());
// Display response message.
System.out.println("Response Message is " +
hpCon.getResponseMessage());
// Get a list of the header fields and a set
// of the header keys.
Map<String, List<String>> hdrMap = hpCon.getHeaderFields();
Set<String> hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrField) {
System.out.println("Key: " + k +
" Value: " + hdrMap.get(k));
}
}
}
The output produced by the program is shown here. 43f course, the e1act
response returned
by www.google.com will vary over time.7
Request method is GET
Response code is 200
Response Message is OK
Here is the header:
Key: Set-Cookie Value:
[PREF=ID=4fbe939441ed966b:TM=1150213711:LM=1150213711:S=Qk81
WCVtvYkJOdh3; expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/;
domain=.google.com]
Key: null Value: [HTTP/1.1 200 OK]
Key: Date Value: [Tue, 13 Jun 2006 15:48:31 GMT]
Key: Content-Type Value: [text/html]
Key: Server Value: [GWS/2.1]
Key: Transfer-Encoding Value: [chunked]
Key: Cache-Control Value: [private]
(he !/I )lass
A relatively recent addition to Java is the !/I class, which
encapsulates a Uni)orm *eso&rce Identi'er (U*I). $E&s are similar to
$EFs.
&n fact, $EFs constitute a subset of $E&s.
A $E& represents a standard way to identify a resource. A$EF also
describes how to access the resource.
)ookies
The java.net package includes classes and interfaces that help
manage cookies and can be used to create a stateful 4as opposed to
stateless7 >TT6 session.
The classes are )ookieHandler4 )ookieManager, and
Htt$)ookie. The interfaces are )ookie*olicy and )ookie,tore.
All but )ookieHandler was added by Java "A C. 4)ookieHandler
was added by J#N <.7
()*+I* ,erver ,ockets
As mentioned earlier, Java has a di-erent socket class that must be
used for creating serverapplications.
The ,erver,ocket class is used to create servers that listen for
either local or
remote client programs to connect to them on published ports.
,erver,ockets are 0uite di-erent from normal ,ockets.
@hen you create a ,erver,ocket, it will register itself with the
system as having an interest in client connections.
The constructors for ,erver,ocket reQect the port number that
you want to accept connections on and, optionally, how long you
want the 0ueue for said port to be.
The 0ueue length tells the system how many client connections it
can leave pending before it should simply refuse connections.
The default is <+.
The constructors might throw an I."#ce$tion under adverse
conditions. >ere are three of its constructorsD
"erver"ocket4int port7 throws &3A1ception
5reates server socket on the specifed portwith a 0ueue length of <+.
"erver"ocket4int port, int ma1Rueue7throws &3A1ception
5reates a server socket on the specifed portwith a ma1imum 0ueue
length of ma1Rueue.
"erver"ocket4int port, int ma1Rueue,&netAddress localAddress7
throws &3A1ception
5reates a server socket on the specifed port with a ma1imum 0ueue
length of ma1Rueue.
3n a multihomed host, localAddress specifes the &,erver,ocket has a
method called acce$t( , which is a blocking call that will wait for a client
to initiate communications and then return with a normal ,ocket that is
then used for communication with the client.
3atagrams
T562&6-style networking is appropriate for most networking needs. &t
provides a serialiBed, predictable, reliable stream of packet data.
This is not without its cost, however.
T56 includes many complicated algorithms for dealing with
congestion control on crowded networks, as well as pessimistic
e1pectations about packet loss. This leads to a somewhat ineScient
way to transport data. #atagrams provide an alternative.
Datagrams are bundles of information passed between machines.
They are somewhat like a hard throw from a well-trained but
blindfolded catcher to the third baseman.
3nce the datagram has been released to its intended target, there
is no assurance that it will arrive or even that someone will be there
to catch it. Fikewise, when the datagram is received, there is no
assurance that it hasnt been damaged in transit or that whoever
sent it is stillthere to receive a response.
Java implements datagrams on top of the $#6 protocol by using two
classesD the 3atagram*acket obHect is the data container, while
the 3atagram,ocket is the mechanism used to send or receive the
3atagram*ackets. Aach is e1amined here.
3atagram,ocket
3atagram,ocket defnes four public constructors. They are shown hereD
#atagram"ocket4 7 throws "ocketA1ception
#atagram"ocket4int port7 throws "ocketA1ception
#atagram"ocket4int port, &netAddress ip+ddress7 throws "ocketA1ception
#atagram"ocket4"ocketAddress address7 throws "ocketA1ception
The frst creates a 3atagram,ocket bound to any unused port on the
local computer.
The second creates a 3atagram,ocket bound to the port specifed by
port.
The third constructsa 3atagram,ocket bound to the specifed port and
InetAddress.
The fourth constructs a 3atagram,ocket bound to the specifed
,ocketAddress.
,ocketAddress is an abstract class that is implemented by the concrete
class Inet,ocketAddress.
Inet,ocketAddress encapsulates an &6 address with a port number. All
can throw a ,ocket"#ce$tion if an error occurs while creating the
socket.
3atagram,ocket defnes many methods. Two of the most
important are send( and receive( , which are shown hereD
void send4#atagram6acket packet7 throws &3A1ception
void receive4#atagram6acket packet7 throws &3A1ception
The send( method sends packet to the port specifed by packet. The
receive ( method waits for a packet to be received from the port
specifed by packet and returns the result.6 address to which this socket
binds.
3ther methods give you access to various attributes associated with
a
3atagram,ocket.>ere is a samplingD
&netAddress get&netAddress4 7 %% &f the socket is connected, then the
address is returned.3therwise, null is returned.
int getFocal6ort4 7 %%Eeturns the number of the local port.
int get6ort4 7 %%Eeturns the number of the port to which the socket is
connected. &t returns K( if the socket is not connected to a port.
boolean is!ound4 7 %% Eeturns true if the socket is bound to an address.
Eeturns false otherwise.
boolean is5onnected4 7 %% Eeturns true if the socket is connected to a
server.
Eeturns false otherwise.
void set"oTimeout4int millis7 throws "ocketA1ception
"ets the time-out period to the number of millisecondspassed in millis.
3atagram*acket
3atagram*acket defnes several constructors. 9our are shown hereD
#atagram6acket4byte dataI J, int si,e7
#atagram6acket4byte dataI J, int o-set, int si,e7
#atagram6acket4byte dataI J, int si,e, &netAddress ip+ddress, int port7
#atagram6acket4byte dataI J, int o-set, int si,e, &netAddress ip+ddress,
int port7
The frst constructor specifes a bu-er that will receive data and the siBe
of a packet.&t is used for receiving data over a 3atagram,ocket.
The second form allows you to specify an o-set into the bu-er at which
data will be stored.
The third form specifes a target address and port, which are used by a
3atagram,ocket to determine where the data in the packet will be sent.
The fourth form transmits packets beginning at the specifed o-set into
the
data. Think of the frst two forms as building an .in bo1,/ and the second
two forms as stuSng and addressing an envelope.
3atagram*acket defnes several methods, including those shown
here, that give access to the address and port number of a packet,
as well as the raw data and its length.
&n general, the get methods are used on packets that are received
and the set methods are used onpackets that will be sent.
&netAddress getAddress4 7 %% Eeturns the address of the source 4for
datagrams
being received7 or destination 4for datagrams
being sent7.
byteI J get#ata4 7 %% Eeturns the byte array of data contained in the
datagram. 8ostly used to retrieve data from the datagram after it has
been received.
int getFength4 7 %% Eeturns the length of the valid data contained in the
byte array that would be returned from the get#ata4 7 method. This may
not e0ual the length
of the whole byte array.
int get3-set4 7 %% Eeturns the starting inde1 of the data.
int get6ort4 7 %%Eeturns the port number.
void setAddress4&netAddress ipAddress7 "ets the address to which a
packet will be sent.The address is specifed by ipAddress.
void set#ata4byteI J data7 %% "ets the data to data, the o-set to Bero, and
the
length to number of bytes in data.
void set#ata4byteI J data, int id1, int siBe7 %% "ets the data to data, the
o-set to id1, and the length to siBe.
void setFength4int siBe7 %% "ets the length of the packet to siBe.
void set6ort4int port7 %% "ets the port to port.
A 3atagram "#am$le
The following e1ample implements a very simple networked
communications client and server. 8essages are typed into the window at
the server and written across the network to the client side, where they
are displayed.
// Demonstrate datagrams.
import java.net.*;
class WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
This sample program is restricted by the 3atagram,ocket constructor to
running between two ports on the local machine. To use the program, run
java WriteServer in one window: this will be the client. Then runjava
WriteServer 1 .This will be the server. Anything that is typed in the
server window will be sent to the client window after a newline is received.

Anda mungkin juga menyukai