Date post: | 14-Apr-2018 |
Category: |
Documents |
Upload: | karthik-shettyan |
View: | 223 times |
Download: | 0 times |
of 56
7/27/2019 Java Networks Final
1/56
Networking Basics
Computers running on the Internet communicate to each other using either the Transmission
Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers.
Instead, you can use the classes in the java.net package. These classes provide system-
independent network communication. However, to decide which Java classes your programsshould use, you do need to understand how TCP and UDP differ.
TCP
When two applications want to communicate to each other reliably, they establish a connection
and send data back and forth over that connection. This is analogous to making a telephone call.
If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial herphone number and she answers. You send data back and forth over the connection by speaking to
one another over the phone lines. Like the phone company, TCP guarantees that data sent from
one end of the connection actually gets to the other end and in the same order it was sent.
Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable communications. The
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples
of applications that require a reliable communication channel. The order in which the data is sentand received over the network is critical to the success of these applications. When HTTP is used
to read from a URL, the data must be received in the order in which it was sent. Otherwise, you
end up with a jumbled HTML file, a corrupt zip file, or some other invalid information.
Definition: TCP(Transmission Control Protocol) is a connection-based protocol that provides a
reliable flow of data between two computers.
UDP
The UDP protocol provides for communication that is not guaranteed between two applications
on the network. UDP is not connection-based like TCP. Rather, it sends independent packets ofdata, called datagrams, from one application to another. Sending datagrams is much like sending
7/27/2019 Java Networks Final
2/56
a letter through the postal service: The order of delivery is not important and is not guaranteed,
and each message is independent of any other.
Definition: UDP(User Datagram Protocol) is a protocol that sends independent packets of
data, called datagrams, from one computer to another with no guarantees about arrival. UDP is
not connection-based like TCP.
For many applications, the guarantee of reliability is critical to the success of the transfer ofinformation from one end of the connection to the other. However, other forms of
communication don't require such strict standards. In fact, they may be slowed down by the extra
overhead or the reliable connection may invalidate the service altogether.
Consider, for example, a clock server that sends the current time to its client when requested todo so. If the client misses a packet, it doesn't really make sense to resend it because the time will
be incorrect when the client receives it on the second try. If the client makes two requests and
receives packets from the server out of order, it doesn't really matter because the client can figureout that the packets are out of order and make another request. The reliability of TCP is
unnecessary in this instance because it causes performance degradation and may hinder theusefulness of the service.
Another example of a service that doesn't need the guarantee of a reliable channel is the pingcommand. The purpose of the ping command is to test the communication between two
programs over the network. In fact, ping needs to know about dropped or out-of-order packets to
determine how good or bad the connection is. A reliable channel would invalidate this servicealtogether.
The UDP protocol provides for communication that is not guaranteed between two applications
on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of
data from one application to another. Sending datagrams is much like sending a letter through themail service: The order of delivery is not important and is not guaranteed, and each message is
independent of any others.
Note: Many firewalls and routers have been configured not to allow UDP packets. If you'rehaving trouble connecting to a service outside your firewall, or if clients are having trouble
connecting to your service, ask your system administrator if UDP is permitted.
Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data
destined for a particular computer arrives through that connection. However, the data may beintended for different applications running on the computer. So how does the computer know towhich application to forward the data? Through the use ofports.
Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP
address, which IP uses to deliver data to the right computer on the network. Ports are identifiedby a 16-bit number, which TCP and UDP use to deliver the data to the right application.
7/27/2019 Java Networks Final
3/56
In connection-based communication such as TCP, a server application binds a socket to a
specific port number. This has the effect of registering the server with the system to receive all
data destined for that port. A client can then rendezvous with the server at the server's port, asillustrated here:
Definition: The TCP and UDP protocols use ports to map incoming data to a particular processrunning on a computer.
In datagram-based communication such as UDP, the datagram packet contains the port number
of its destination and UDP routes the packet to the appropriate application, as illustrated in this
figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known servicessuch as HTTP and FTP and other system services. These ports are called well-known ports. Your
applications should not attempt to bind to them.
Networking Classes in the JDK
Through the classes in java.net, Java programs can use TCP or UDP to communicate over the
Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to
communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket
classes are for use with UDP.
Working with URLs
URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on
the Internet. You provide URLs to your favorite Web browser so that it can locate files on theInternet in the same way that you provide addresses on letters so that the post office can locate
your correspondents.
7/27/2019 Java Networks Final
4/56
7/27/2019 Java Networks Final
5/56
Host Name The name of the machine on which the resource lives.
Filename The pathname to the file on the machine.
Port
NumberThe port number to which to connect (typically optional).
ReferenceA reference to a named anchor within a resource that usually identifies a
specific location within a file (typically optional).
For many protocols, the host name and the filename are required, while the port number
and reference are optional. For example, the resource name for an HTTP URL mustspecify a server on the network (Host Name) and the path to the document on that
machine (Filename); it also can specify a port number and a reference. In the URL for the
Java Web site java.sun.com is the host name and an empty path or the trailing slash
is shorthand for the file named /index.html.
Creating a URL
The easiest way to create a URL object is from a String that represents
the human-readable form of the URL address. This is typically the form
that another person will use for a URL. For example, the URL for the
Gamelan site, which is a directory of Java resources, takes the
following form:
http://www.gamelan.com/
In your Java program, you can use a String containing this text to
create a URL object:
URL gamelan = new URL("http://www.gamelan.com/");
The URL object created above represents an absolute URL. An absolute
URL contains all of the information necessary to reach the resource in
question. You can also create URL objects from a relative URL address.
Creating a URL Relative to Another
A relative URL contains only enough information to reach the resource
relative to (or in the context of) another URL.
http://www.gamelan.com/http://www.gamelan.com/7/27/2019 Java Networks Final
6/56
Relative URL specifications are often used within HTML files. For example, suppose
you write an HTML file called JoesHomePage.html. Within this page, are links to
other pages, PicturesOfMe.html and MyKids.html, that are on the same machine
and in the same directory as JoesHomePage.html. The links to
PicturesOfMe.html and MyKids.html from JoesHomePage.html could be
specified just as filenames, like this:
Pictures of Me
Pictures of My Kids
These URL addresses are relative URLs. That is, the URLs are specified
relative to the file in which they are contained--JoesHomePage.html.
In your Java programs, you can create a URL object from a relative URL specification.
For example, suppose you know two URLs at the Gamelan site:
http://www.gamelan.com/pages/Gamelan.game.html
http://www.gamelan.com/pages/Gamelan.net.html
You can create URL objects for these pages relative to their common
base URL: http://www.gamelan.com/pages/ like this:
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "Gamelan.game.html");
URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
This code snippet uses the URL constructor that lets you create a URL
object from another URL object (the base) and a relative URL
specification. The general form of this constructor is:
URL(URL baseURL, String relativeURL)
The first argument is a URL object that specifies the base of the new
URL. The second argument is a String that specifies the rest of the
resource name relative to the base. IfbaseURL is null, then this
constructor treats relativeURL like an absolute URL specification.
Conversely, ifrelativeURL is an absolute URL specification, then the
constructor ignores baseURL.
This constructor is also useful for creating URL objects for named anchors (also called
references) within a file. For example, suppose the Gamelan.network.html file has
a named anchor called BOTTOM at the bottom of the file. You can use the relative URL
constructor to create a URL object for it like this:
7/27/2019 Java Networks Final
7/56
URL gamelanNetworkBottom = new URL(gamelanNetwork,
"#BOTTOM");
Other URL Constructors
The URL class provides two additional constructors for creating a URLobject. These constructors are useful when you are working with URLs,
such as HTTP URLs, that have host name, filename, port number, and
reference components in the resource name portion of the URL. These
two constructors are useful when you do not have a String containing
the complete URL specification, but you do know various components
of the URL.
For example, suppose you design a network browsing panel similar to a file browsing
panel that allows users to choose the protocol, host name, port number, and filename.You can construct a URL from the panel's components. The first constructor creates a
URL object from a protocol, host name, and filename. The following code snippet creates
a URL to the Gamelan.net.html file at the Gamelan site:
new URL("http", "www.gamelan.com",
"/pages/Gamelan.net.html");
This is equivalent to
new URL("http://www.gamelan.com/pages/Gamelan.net.html");
The first argument is the protocol, the second is the host name, andthe last is the pathname of the file. Note that the filename contains a
forward slash at the beginning. This indicates that the filename is
specified from the root of the host.
The final URL constructor adds the port number to the list of arguments used in the
previous constructor:
URL gamelan = new URL("http", "www.gamelan.com", 80,
"pages/Gamelan.network.html");
This creates a URL object for the following URL:
http://www.gamelan.com:80/pages/Gamelan.network.html
If you construct a URL object using one of these constructors, you can
get a String containing the complete URL address by using the URL
object's toString method or the equivalent toExternalForm method.
7/27/2019 Java Networks Final
8/56
URL addresses with Special characters
Some URL addresses contain special characters, for example the space
character. Like this:
http://foo.com/hello world/To make theses characters legal they need to encoded before passing
them to the URL constructor.
URL url = new URL("http://foo.com/hello%20world");
Encoding the special character(s) in this example is easy as there is
only one character that needs encoding, but for URL addresses that
have several of these characters or if you are unsure when writing your
code what URL addresses you will need to access, you can use the
multi-argument constructors of the java.net.URI class to
automatically take care of the encoding for you.
URI uri = new URI("http", "foo.com", "/hello world/", "");
And then convert the URI to a URL.
URL url = uri.toURL();
MalformedURLException
Each of the four URL constructors throws a MalformedURLException if
the arguments to the constructor refer to a null or unknown protocol.
Typically, you want to catch and handle this exception by embedding
your URL constructor statements in a try/catch pair, like this:
try {
URL myURL = new URL(. . .)
} catch (MalformedURLException e) {. . .
// exception handler code here
. . .
}
See Exceptions for information about handling exceptions.
http://java.sun.com/javase/7/docs/api/java/net/URI.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/essential/exceptions/index.htmlhttp://java.sun.com/javase/7/docs/api/java/net/URI.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/essential/exceptions/index.html7/27/2019 Java Networks Final
9/56
Note: URLs are "write-once" objects. Once you've created a URL object,
you cannot change any of its attributes (protocol, host name, filename,
or port number).
Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the
protocol, authority, host name, port number, path, query, filename, and reference from a
URL using these accessor methods:
getProtocol Returns the protocol identifier
component of the URL.
getAuthority Returns the authority component of the URL.getHost
Returns the host name component of theURL.getPort
Returns the port number component of
the URL. The getPort method returns
an integer that is the port number. If the
port is not set, getPort returns -1.getPath
Returns the path component of this URL.getQuery
Returns the query component of this
URL.getFile
Returns the filename component of the
URL. The getFile method returns the
same as getPath, plus the
concatenation of the value ofgetQuery, if any.
getRef
Returns the reference
component of the URL.
Note: Remember that not all URL addresses contain these
components. The URL class provides these methods because
HTTP URLs do contain these components and are perhaps the
most commonly used URLs. The URL class is somewhat HTTP-
centric.
7/27/2019 Java Networks Final
10/56
You can use these getXXXmethods to get information about
the URL regardless of the constructor that you used to
create the URL object.
The URL class, along with these accessor methods, frees you
from ever having to parse URLs again! Given any stringspecification of a URL, just create a new URL object and
call any of the accessor methods for the information you
need. This small example program creates a URL from a
string specification and then uses the URL object's
accessor methods to parse the URL:
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception
{
URL aURL = new
URL("http://java.sun.com:80/docs/books/tutorial"+"/index.ht
ml?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " +
aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
Here's the output displayed by the program:
protocol = http
authority = java.sun.com:80
host = java.sun.comport = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
Reading Directly from a URL
7/27/2019 Java Networks Final
11/56
After you've successfully created a URL, you can call the URL's openStream()
method to get a stream from which you can read the contents of the URL. The
openStream() method returns a java.io.InputStream object, so reading from
a URL is as easy as reading from an input stream.
The following small Java program uses openStream() to get an input stream on theURL http://www.yahoo.com/ . It then opens a BufferedReader on the input
stream and reads from the BufferedReader thereby reading from the URL.
Everything read is copied to the standard output stream:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception{
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
When you run the program, you should see, scrolling by in your command window, the
HTML commands and textual content from the HTML file located at
http://www.yahoo.com/ . Alternatively, the program might hang or you might see
an exception stack trace. If either of the latter two events occurs, you may have to set the
proxy host so that the program can find the Yahoo server.
Connecting to a URL
http://java.sun.com/javase/7/docs/api/java/io/InputStream.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/_setProxy.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/_setProxy.htmlhttp://java.sun.com/javase/7/docs/api/java/io/InputStream.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/_setProxy.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/_setProxy.html7/27/2019 Java Networks Final
12/56
After you've successfully created a URL object, you can call the URL object's
openConnectionmethod to get a URLConnection object, or one of its protocol
specific subclasses, e.g. java.net.HttpURLConnection
You can use this URLConnection object to setup parameters and general request
properties that you may need before connecting. Connection to the remote object
represented by the URL is only initiated when the URLConnection.connect
method is called. When you do this you are initializing a communication link between
your Java program and the URL over the network. For example, you can open a
connection to the Yahoo site with the following code:
try {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
yahooConnection.connect();
} catch (MalformedURLException e) { // new URL() failed
. . .
} catch (IOException e) { // openConnection()
failed
. . .
}
A new URLConnection object is created every time by calling the
openConnection method of the protocol handler for this URL.
You are not always required to explicitly call the connectmethod to initiate theconnection. Operations that depend on being connected, like getInputStream,
getOutputStream, etc, will implicitly perform the connection, if necessary.
Now that you've successfully connected to your URL, you can use the
URLConnection object to perform actions such as reading from or writing to the
connection. The next section shows you how.
URLConnection class
The abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL. Instances of this class can be
used both to read from and to write to the resource referenced by the URL. In general,
creating a connection to a URL is a multistep process:
http://java.sun.com/javase/7/docs/api/java/net/HttpURLConnection.htmlhttp://java.sun.com/javase/7/docs/api/java/net/HttpURLConnection.html7/27/2019 Java Networks Final
13/56
The connection object is created by invoking the openConnection method on
a URL.
The setup parameters and general request properties are manipulated.
The actual connection to the remote object is made, using the connect method.
The remote object becomes available. The header fields and the contents of the
remote object can be accessed.
The setup parameters are modified using the following methods:
1. setAllowUserInteraction.
2. setDoInput-setDoOutput- Sets the value of the doOutput field for
this URLConnection to the specified value.
3. setIfModifiedSince
4. setUseCaches
and the general request properties are modified using the method:
1. setRequestProperty-
Default values for the AllowUserInteraction and UseCaches parameters can be
set using the methods setDefaultAllowUserInteraction and
setDefaultUseCaches .
Each of the above set methods has a corresponding get method to retrieve the value of
the parameter or general request property. The specific parameters and general request
properties that are applicable are protocol specific.
The following methods are used to access the header fields and the contents after the
connection is made to the remote object:
1.getContent
2.getHeaderField
3.getInputStream
4.getOutputStream
Certain header fields are accessed frequently. The methods:
1.getContentEncoding
2.getContentLength
7/27/2019 Java Networks Final
14/56
3.getContentType
4.getDate
5.getExpiration
6.getLastModifed
provide convenient access to these fields. The getContentType method is used by the
getContent method to determine the type of the remote object; subclasses may find it
convenient to override the getContentTypemethod.
Constructor Summary
protected URLConnection(URL url)
Constructs a URL connection to the specified URL.
Method Summary
void addRequestProperty(String key, String value)
Adds a general request property specified by a
key-value pair.
abstract void connect()Opens a communications link to the resource
referenced by this URL, if such a connection has not
already been established.
booleangetAllowUserInteraction()
http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#URLConnection(java.net.URL)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#addRequestProperty(java.lang.String,%20java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#connect()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getAllowUserInteraction()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#URLConnection(java.net.URL)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#addRequestProperty(java.lang.String,%20java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#connect()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getAllowUserInteraction()7/27/2019 Java Networks Final
15/56
Returns the value of the allowUserInteraction
field for this object.
Object getContent()
Retrieves the contents of this URL connection.
Object getContent(Class[] classes)
Retrieves the contents of this URL connection.
String getContentEncoding()
Returns the value of the content-encoding
header field.
int getContentLength()Returns the value of the content-length header
field.
String getContentType()
Returns the value of the content-type header
field.
long getDate()
Returns the value of the date header field.
static boolean getDefaultAllowUserInteraction()
Returns the default value of the
allowUserInteraction field.
static String getDefaultRequestProperty(String key)
Deprecated.The instance specific
getRequestProperty method should be used after an
appropriate instance of URLConnection is obtained.
boolean getDefaultUseCaches()
Returns the default value of a
URLConnection'suseCaches flag.
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContent()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContent(java.lang.Class[])http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentEncoding()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentLength()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentType()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDate()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultAllowUserInteraction()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultRequestProperty(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultUseCaches()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContent()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContent(java.lang.Class[])http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentEncoding()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentLength()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getContentType()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDate()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultAllowUserInteraction()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultRequestProperty(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDefaultUseCaches()7/27/2019 Java Networks Final
16/56
boolean getDoInput()
Returns the value of this
URLConnection'sdoInput flag.
boolean getDoOutput()Returns the value of this
URLConnection'sdoOutput flag.
long getExpiration()
Returns the value of the expires header field.
static FileNam
eMap
getFileNameMap()
Loads filename map (a mimetable) from a data
file.
String getHeaderField(int n)
Returns the value for the nth header field.
String getHeaderField(String name)
Returns the value of the named header field.
long getHeaderFieldDate(String name, long Default)
Returns the value of the named field parsed asdate.
int getHeaderFieldInt(String name, int Default)
Returns the value of the named field parsed as a
number.
String getHeaderFieldKey(int n)
Returns the key for the nth header field.
Map getHeaderFields()
Returns an unmodifiable Map of the header
fields.
longgetIfModifiedSince()
http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDoInput()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDoOutput()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getExpiration()http://download.oracle.com/javase/1.4.2/docs/api/java/net/FileNameMap.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/FileNameMap.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getFileNameMap()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderField(int)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderField(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldDate(java.lang.String,%20long)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldInt(java.lang.String,%20int)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldKey(int)http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFields()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getIfModifiedSince()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDoInput()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getDoOutput()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getExpiration()http://download.oracle.com/javase/1.4.2/docs/api/java/net/FileNameMap.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/FileNameMap.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getFileNameMap()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderField(int)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderField(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldDate(java.lang.String,%20long)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldInt(java.lang.String,%20int)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFieldKey(int)http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getHeaderFields()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getIfModifiedSince()7/27/2019 Java Networks Final
17/56
Returns the value of this object's
ifModifiedSince field.
InputStream getInputStream()
Returns an input stream that reads from thisopen connection.
long getLastModified()
Returns the value of the last-modified header
field.
OutputStrea
m
getOutputStream()
Returns an output stream that writes to this
connection.
Permission getPermission()
Returns a permission object representing the
permission necessary to make the connection
represented by this object.
Map getRequestProperties()
Returns an unmodifiable Map of general request
properties for this connection.
String getRequestProperty(String key)
Returns the value of the named general request
property for this connection.
URL getURL()
Returns the value of this URLConnection'sURL
field.
boolean getUseCaches()
Returns the value of this
URLConnection'suseCaches field.
static String guessContentTypeFromName(String fname)
http://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getInputStream()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getLastModified()http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getOutputStream()http://download.oracle.com/javase/1.4.2/docs/api/java/security/Permission.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getPermission()http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getRequestProperties()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getRequestProperty(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getURL()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getUseCaches()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#guessContentTypeFromName(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getInputStream()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getLastModified()http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getOutputStream()http://download.oracle.com/javase/1.4.2/docs/api/java/security/Permission.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getPermission()http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getRequestProperties()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getRequestProperty(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URL.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getURL()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#getUseCaches()http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#guessContentTypeFromName(java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html7/27/2019 Java Networks Final
18/56
Tries to determine the content type of an object,
based on the specified "file" component of a URL.
static String guessContentTypeFromStream(InputStream is)
Tries to determine the type of an input streambased on the characters at the beginning of the input
stream.
void setAllowUserInteraction(boolean allowuserinter
action)
Set the value of the allowUserInteraction field
of this URLConnection.
static void setContentHandlerFactory(ContentHandlerFactoryfac)
Sets the ContentHandlerFactory of an
application.
static void setDefaultAllowUserInteraction(boolean default
allowuserinteraction)
Sets the default value of the
allowUserInteraction field for all future
URLConnection objects to the specified value.
static void setDefaultRequestProperty(String key,
String value)
Deprecated.The instance specific
setRequestProperty method should be used after an
appropriate instance of URLConnection is obtained.
void setDefaultUseCaches(boolean defaultusecaches)
Sets the default value of the useCaches field tothe specified value.
void setDoInput(boolean doinput)
Sets the value of the doInput field for this
URLConnection to the specified value.
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#guessContentTypeFromStream(java.io.InputStream)http://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setAllowUserInteraction(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setContentHandlerFactory(java.net.ContentHandlerFactory)http://download.oracle.com/javase/1.4.2/docs/api/java/net/ContentHandlerFactory.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultAllowUserInteraction(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultRequestProperty(java.lang.String,%20java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultUseCaches(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDoInput(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#guessContentTypeFromStream(java.io.InputStream)http://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setAllowUserInteraction(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setContentHandlerFactory(java.net.ContentHandlerFactory)http://download.oracle.com/javase/1.4.2/docs/api/java/net/ContentHandlerFactory.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultAllowUserInteraction(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultRequestProperty(java.lang.String,%20java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDefaultUseCaches(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDoInput(boolean)7/27/2019 Java Networks Final
19/56
void setDoOutput(boolean dooutput)
Sets the value of the doOutput field for this
URLConnection to the specified value.
static void setFileNameMap(FileNameMap map)Sets the FileNameMap.
void setIfModifiedSince(long ifmodifiedsince)
Sets the value of the ifModifiedSince field of
this URLConnection to the specified value.
void setRequestProperty(String key, String value)
Sets the general request property.
void setUseCaches(boolean usecaches)
Sets the value of the useCaches field of this
URLConnection to the specified value.
String toString()
Returns a String representation of this URL
connection.
Reading from and Writing to a URLConnection
The URLConnection class contains many methods that let you communicate with the
URL over the network. URLConnection is an HTTP-centric class; that is, many of its
methods are useful only when you are working with HTTP URLs. However, most URLprotocols allow you to read from and write to the connection. This section describes both
functions.
Reading from aURLConnection
The following program performs the same function as the URLReader program shown
in Reading Directly from a URL.
http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDoOutput(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setIfModifiedSince(long)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setIfModifiedSince(long)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setIfModifiedSince(long)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setUseCaches(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#toString()http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setDoOutput(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setFileNameMap(java.net.FileNameMap)http://download.oracle.com/javase/1.4.2/docs/api/java/net/FileNameMap.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setIfModifiedSince(long)http://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setRequestProperty(java.lang.String,%20java.lang.String)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#setUseCaches(boolean)http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlhttp://download.oracle.com/javase/1.4.2/docs/api/java/net/URLConnection.html#toString()7/27/2019 Java Networks Final
20/56
However, rather than getting an input stream directly from the URL, this program
explicitly retrieves a URLConnection object and gets an input stream from the
connection. The connection is opened implicitly by calling getInputStream. Then,
like URLReader, this program creates a BufferedReader on the input stream and
reads from it. The bold statements highlight the differences between this example and the
previous
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The output from this program is identical to the output from the program that opens a
stream directly from the URL. You can use either way to read from a URL. However,reading from aURLConnection instead of reading directly from a URL might be more
useful. This is because you can use the URLConnection object for other tasks (like
writing to the URL) at the same time.
Again, if the program hangs or you see an error message, you may have to set the proxy
host so that the program can find the Yahoo server.
Writing to a URLConnection
Many HTML pages containforms-- text fields and other GUI objects that let you enterdata to send to the server. After you type in the required information and initiate the
query by clicking a button, your Web browser writes the data to the URL over the
network. At the other end the server receives the data, processes it, and then sends you a
response, usually in the form of a new HTML page.
http://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/readingURL.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/readingURL.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/urls/readingURL.html7/27/2019 Java Networks Final
21/56
Connecting to Server
What Is a Socket?
7/27/2019 Java Networks Final
22/56
Normally, a server runs on a specific computer and has a socket that is bound to a
specific port number. The server just waits, listening to the socket for a client to make a
connection request.
On the client-side: The client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connectionrequest, the client tries to rendezvous with the server on the server's machine and port.
The client also needs to identify itself to the server so it binds to a local port number thatit will use during this connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server
gets a new socket bound to the same local port and also has its remote endpoint set to the
address and port of the client. It needs a new socket so that it can continue to listen to the
original socket for connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the
client can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition: Asocketis one endpoint of a two-way communication link between two
programs running on the network. A socket is bound to a port number so that the TCP
layer can identify the application that data is destined to be sent.
An endpoint is a combination of an IP address and a port number. Every TCP connection
can be uniquely identified by its two endpoints. That way you can have multiple
connections between your host and the server.
The java.net package in the Java platform provides a class, Socket, that implements
one side of a two-way connection between your Java program and another program on
the network. The Socket class sits on top of a platform-dependent implementation,
hiding the details of any particular system from your Java program. By using the
java.net.Socket class instead of relying on native code, your Java programs can
communicate over the network in a platform-independent fashion.
7/27/2019 Java Networks Final
23/56
Additionally, java.net includes the ServerSocket class, which implements a
socket that servers can use to listen for and accept connections to clients. This lesson
shows you how to use the Socket and ServerSocket classes.
If you are trying to connect to the Web, the URL class and related classes
(URLConnection, URLEncoder) are probably more appropriate than the socket
classes. In fact, URLs are a relatively high-level connection to the Web and use sockets
as part of the underlying implementation.
Reading from and Writing to a Socket
Let's look at a simple example that illustrates how a program can establish a connection
to a server program using the Socket class and then, how the client can send data to and
receive data from the server through the socket.
The example program implements a client, EchoClient, that connects to the Echo
server. The Echo server simply receives data from its client and echoes it back.
EchoClient creates a socket thereby getting a connection to the Echo server. It reads
input from the user on the standard input stream, and then forwards that text to the Echo
server by writing the text to the socket. The server echoes the input back through the
socket to the client. The client program reads and displays the data passed back to it from
the server:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String host="localhost";
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
InetAddress address= InetAddress.getByName(host);
echoSocket = new Socket(address, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
7/27/2019 Java Networks Final
24/56
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection .");
System.exit(1);
}
BufferedReaderstdIn = new BufferedReader(
newInputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The EchoServer class implements the server who listens at
port no 4444 for client requests.Only one client is served.
public class EchoServer {
7/27/2019 Java Networks Final
25/56
public static void main(String[] args) throws Exception {
// create socket
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a
connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
BufferedReader in = new BufferedReader(new
InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true);
// waits for data and reads it in until
connection dies
// readLine() blocks until the server receives
a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);System.out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
7/27/2019 Java Networks Final
26/56
out.close();
in.close();
clientSocket.close();
System.exit(1);
}
}
}
This client program is straightforward and simple because the Echo server implements a
simple protocol. The client sends text to the server, and the server echoes it back. When
your client programs are talking to a more complicated server such as an HTTP server,
your client program will also be more complicated. However, the basics are much the
same as they are in this program:
Open a socket.
Open an input stream and output stream
to the socket.
Read from and write to the stream
according to the server's protocol.
Close the streams.
Close the socket.
Only step 3 differs from client to client, depending on the server. The other steps remain
largely the same.
Serving Multiple Clients at a time.
There is one problem with the simple server in the preceding example.
7/27/2019 Java Networks Final
27/56
Suppose we want to allow multiple clients to connect to our server at thesame time. Typically, a server runs constantly on a server computer, andclients from all over the Internet may want to use the server at the sametime. Rejecting multiple connections allows any one client to monopolizethe service by connecting to it for a long time. We can do much better
through the magic of threads.Every time we know the program has established a new socket connection,thatis, when the call to accept was successful, we will launch a new thread to takecare of the connection between the server and thatclient. The main program will
just go back and wait for the next connection.
import java.io.*;
import java.net.*;
public class ThreadedEchoServer {
public static void main(String[] args) throws Exception {
// create socket
int port = 4444;
int i=1;
try{
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
for(;;) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
7/27/2019 Java Networks Final
28/56
System.err.println("Accepted connection from client"+ i);
ClientThread ct=new ClientThread(clientSocket,i);
ct.start();
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
class ClientThread extends Thread
{
Socket sc;
int counter;
BufferedReader in;
PrintWriter out;
public ClientThread(Socket sc,int counter)
{this.sc=sc;
this.counter=counter;
}
public void run()
{
7/27/2019 Java Networks Final
29/56
try{
// open up IO streams
BufferedReader in = new BufferedReader(newInputStreamReader(sc.getInputStream()));
PrintWriter out = new PrintWriter(sc.getOutputStream(), true/*autoFlush */);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
System.out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client:"+ counter);
out.close();
in.close();
sc.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
7/27/2019 Java Networks Final
30/56
}
Methods in java.net.Socket
Socket(String host, int port)
creates a socket and connects it to a port on a remote host.
Socket()
creates a socket that has not yet been connected.
void connect(SocketAddress address)
connects this socket to the given address. (Since SDK 1.4)
void connect(SocketAddress address, int timeout)
connects this socket to the given address or returns if the timeinterval expired
boolean isConnected()
returns true if the socket is connected. (Since SDK 1.4)
void close()
closes the socket. boolean isClosed()
returns true if the socket is closed. (Since SDK 1.4)
InputStream getInputStream()
gets the input stream to read from the socket.
OutputStream getOutputStream()
gets an output stream to write to this socket.
void setSoTimeout(int timeout)sets the blocking time for read requests on this Socket. If the
timeout is reached, then an InterruptedIOException is
raised.
void shutdownOutput()
sets the output stream to "end of stream."
7/27/2019 Java Networks Final
31/56
void shutdownInput()
sets the input stream to "end of stream."
boolean isOutputShutdown
returns true if output has been shut down. (Since SDK 1.4)
boolean isInputShutdown
returns true if input has been shut down
Methods in java.net.ServerSocket
ServerSocket(int port) throws IOException
creates a server socket that monitors a port.
Socket accept() throws IOException
waits for a connection. This method will block (that is, idle) thecurrent thread until the connection is made. The method returns aSocket object through which the program can communicate with
the connecting client.
void close() throws IOExceptioncloses the server socket.
Sending E-Mail
To send e-mail, you make a socket connection to port 25, the SMTP port.SMTP is the Simple Mail Transport Protocol that describes the format fore-mail messages. You can connect to any server that runs an SMTP
service. On UNIX machines, that service is typically implemented by thesendmail daemon.
Here are the details:1. Open a socket to your host.2. Socket s = new Socket("mail.yourserver.com", 25);
// 25 is SMTP
7/27/2019 Java Networks Final
32/56
3. PrintWriter out = new
PrintWriter(s.getOutputStream());
2. Send the following information to the print stream:3. HELO sending host
4. MAIL FROM:
5. RCPT TO: 6. DATA
7. mail message
8. (any number of lines)
9. .
10. QUIT
The SMTP specification (RFC 821) states that lines must be terminatedwith \r followed by \n.
Program to create a client that sends a mail to a server in the localhost like
DevNullSMTP server
Import java.io.*;
Import java.net.*;
public class SMTPDemo {
public static void main(String args[]) throws IOException,
UnknownHostException {
String msgFile = "file1.txt";
String from = "[email protected]";
String to = "[email protected]";
String mailHost = "localhost";
SMTP mail = new SMTP(mailHost);
if (mail != null) {
7/27/2019 Java Networks Final
33/56
if (mail.send(new FileReader(msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP server failed!");
}
}
System.out.println("Done.");
}
static class SMTP {
private final static int SMTP_PORT = 25;
InetAddress mailHost;
InetAddress localhost;
BufferedReader in;
PrintWriter out;
public SMTP(String host) throws UnknownHostException {
mailHost = InetAddress.getByName(host);
localhost = InetAddress.getLocalHost();
System.out.println("mailhost = " + mailHost);
System.out.println("localhost= " + localhost);
System.out.println("SMTP constructor done\n");
7/27/2019 Java Networks Final
34/56
}
public boolean send(FileReader msgFileReader, String from, String to)
throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false;
}
inn = smtpPipe.getInputStream();
outt = smtpPipe.getOutputStream();
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return false;
}
String initialID = in.readLine();
System.out.println(initialID);
System.out.println("HELO " + localhost.getHostName());
out.println("HELO " + localhost.getHostName());
String welcome = in.readLine();
System.out.println(welcome);
7/27/2019 Java Networks Final
35/56
System.out.println("MAIL From:");
out.println("MAIL From:");
String senderOK = in.readLine();
System.out.println(senderOK);
System.out.println("RCPT TO:");
out.println("RCPT TO:");
String recipientOK = in.readLine();
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
while ((line = msg.readLine()) != null) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine();
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
7/27/2019 Java Networks Final
36/56
Internet AddressingEvery computer on the Internet has an address. An Internet address is a
number that uniquely identifies each computer on the Net. Originally, all Internetaddresses consisted of 32-bit values. This address type was specified by IPv4(Internet Protocol,version 4). However, a new addressing scheme, called IPv6
(Internet Protocol, version6) has come into play. IPv6 uses a 128-bit value torepresent an address. Although there are several reasons for and advantages toIPv6, the main one is that it supports a muchlarger address space than doesIPv4. Fortunately, IPv6 is downwardly compatible with IPv4. Currently, IPv4 is byfar the most widely used scheme, but this situation is likelyto change over time.Because of the emerging importance of IPv6, Java 2, version 1.4 has beguntoadd support for it. However, at the time of this writing, IPv6 is not supported byall environments. Furthermore, for the next few years, IPv4 will continue to be thedominantform of addressing. For these reasons, the form of Internet addressesdiscussed here, and used in this chapter, are the IPv4 form. As mentioned, IPv4is, loosely, a subsetof IPv6, and the material contained in this chapter is largelyapplicable to both formsof addressing.There are 32 bits in an IPv4 IP address, and we often refer to them as asequenceof four numbers between 0 and 255 separated by dots (.). This makesthem easier toremember, because they are not randomly assignedthey arehierarchically assigned.The first few bits define which class of network, lettered A, B, C, D, or E, theaddress represents. Most Internet users are on a class C network, since there
7/27/2019 Java Networks Final
37/56
are over two million networks in class C. The first byte of a class C network isbetween 192 and 224,with the last byte actually identifying an individualcomputer among the 256 allowed on a single class C network. This schemeallows for half a billion devices to live on class C networks.
Domain Naming Service (DNS)The Internet wouldnt be a very friendly place to navigate if everyone had to referto their addresses as numbers. For example, it is difficult to imagine seeinghttp://192.9.9.1/ at the bottom of an advertisement. Thankfully, a clearing houseexists for a parallel hierarchy of names to go with all these numbers. It is calledthe Domain Naming Service (DNS). Just as the four numbers of an IP addressdescribe anetwork hierarchy from left to right, the name of an Internet address,called its domain name, describes a machines location in a name space, fromright to left. For example,www.osborne.com is in the COM domain (reserved forU.S. commercial sites), it is called osborne (after the company name), and www
is the name of the specific computer that is Osbornes web server. wwwcorresponds to the rightmost number in the equivalent IP address.Java and the NetNow that the stage has been set, lets take a look at how Java relates to all ofthese network concepts. Java supports TCP/IP both by extending the alreadyestablished stream I/O interface and by adding the features required tobuild I/Oobjects across the network. Java supports both the TCP and UDP protocolfamilies. TCP is used for reliable stream-based I/O across the network. UDPsupportsa simpler, hence faster, point-to-point datagram-oriented model.
The Networking Classes and InterfacesThe classes contained in the java.net package are listed here:
7/27/2019 Java Networks Final
38/56
The java.net packages interfaces are listed here:
InetAddress
Whether you are making a phone call, sending mail, or establishing a connectionacrossthe Internet, addresses are fundamental. The InetAddress class is used toencapsulate both the numerical IP address we discussed earlier and the domainname for thataddress. You interact with this class by using the name of an IPhost, which is more convenient and understandable than its IP address. TheInetAddress class hides the number inside. As of Java 2, version 1.4,InetAddress can handle both IPv4 and IPv6 addresses. This discussion assumesIPv4.
Factory MethodsThe InetAddress class has no visible constructors. To create an InetAddressobject,you have to use one of the available factory methods. Factory methodsare merely a convention whereby static methods in a class return an instance ofthat class. This is done in lieu of overloading a constructor with various
parameter lists when having unique method names makes the results muchclearer. Three commonly used InetAddress factory methods are shown here.
The getLocalHost( ) method simply returns the InetAddress object thatrepresents the local host. The getByName( ) method returns an InetAddress for ahost name passed to it. If these methods are unable to resolve the host name,they throw an UnknownHostException.On the Internet, it is common for a single name to be used to represent severalmachines. In the world of web servers, this is one way to provide some degree of
7/27/2019 Java Networks Final
39/56
scaling. The getAllByName( ) factory method returns an array of InetAddressesthat represent all of the addresses that a particular name resolves to. It will alsothrow anUnknownHostException if it cant resolve the name to at least oneaddress.Java 2, version 1.4 also includes the factory method getByAddress( ), which
takes an IPaddress and returns an InetAddress object. Either an IPv4 or an IPv6address can be used.The following example prints the addresses and names of the local machine andtwo well-known Internet web sites:// 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
7/27/2019 Java Networks Final
40/56
Internet addresses are looked up in a series of hierarchically cached servers.That means that your local computer might know a particular name-to-IP-addressmapping automatically, such as for itself and nearby servers. For other names, itmay ask a localDNS server for IP address information. If that server doesnt havea particular address,it can go to a remote site and ask for it. This can continue allthe way up to the rootserver, called InterNIC (internic.net). This process might take a long time, so it iswiseto structure your code so that you cache IP address information locallyrather than lookit up repeatedly.
What Is a Network Interface?
A network interface is the point of interconnection between a computer and aprivate or public network. A network interface is generally a network interfacecard (NIC), but does not have to have a physical form. Instead, the networkinterface can be implemented in software. For example, the loopback interface(127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical device but a piece ofsoftware simulating a network interface. The loopback interface is commonlyused in test environments.
Thejava.net.NetworkInterface class represents both types of interfaces.
NetworkInterface is useful for a multihomed system, which is a system withmultiple NICs. Using NetworkInterface, you can specify which NIC to use for aparticular network activity.
For example, assume you have a machine with two configured NICs, and youwant to send data to a server. You create a socket like this:
http://java.sun.com/javase/7/docs/api/java/net/NetworkInterface.htmlhttp://java.sun.com/javase/7/docs/api/java/net/NetworkInterface.html7/27/2019 Java Networks Final
41/56
Socket soc = new java.net.Socket();soc.connect(new InetSocketAddress(address, port));
To send the data, the system determines which interface will be used. However,if you have a preference or otherwise need to specify which NIC to use, you canquery the system for the appropriate interfaces and find an address on theinterface you want to use. When you create the socket and bind it to thataddress, the system will use the associated interface. For example:NetworkInterface nif = NetworkInterface.getByName("bge0");Enumeration nifAddresses = nif.getInetAddresses();
Socket soc = new java.net.Socket();soc.bind(nifAddresses.nextElement());soc.connect(new InetSocketAddress(address, port));
You can also use NetworkInterface to identify the local interface on which a
multicast group is to be joined. For example:
NetworkInterfacenif = NetworkInterface.getByName("bge0");
MulticastSocket() ms = new MulticastSocket();ms.joinGroup(new InetSocketAddress(hostname, port) , nif);
NetworkInterface can be used with Java APIs in many other ways beyond thetwo uses described here.
Retrieving Network InterfacesThe NetworkInterface class has no public constructor. Therefore, you cannot justcreate a new instance of this class with the new operator. Instead, the followingstatic methods are available so that you can retrieve the interface details from thesystem: getByInetAddress(), getByName(), and getNetworkInterfaces(). The firsttwo methods are used when you already know the IP address or the name of theparticular interface. The third method, getNetworkInterfaces() returns thecomplete list of interfaces on the machine.Network interfaces can be hierarchically organized. The NetworkInterface classincludes two methods, getParent() and getSubInterfaces(), that are pertinent to a
network interface hierarchy. The getParent() method returns the parentNetworkInterface of an interface. If a network interface is a subinterface,getParent() returns a non-null value. The getSubInterfaces() method returns allthe subinterfaces of a network interface.The following example program lists the name of all the network interfaces andsubinterfaces (if any exist) on a machine.
7/27/2019 Java Networks Final
42/56
7/27/2019 Java Networks Final
43/56
One of the most useful pieces of information you can get from a networkinterface is the list of IP addresses that are assigned to it. You can obtain thisinformation from a NetworkInterface instance by using one of two methods. Thefirst method, getInetAddresses(), returns an Enumeration of InetAddress. Theother method, getInterfaceAddresses(), returns a list ofjava.net.InterfaceAddress
instances. This method is used when you need more information about aninterface address beyond its IP address. For example, you might need additionalinformation about the subnet mask and broadcast address when the address isan IPv4 address, and a network prefix length in the case of an IPv6 address.The following example program lists all the network interfaces and theiraddresses on a machine:
import java.io.*;import java.net.*;importjava.util.*;
import static java.lang.System.out;
public class ListNets{public static void main(String args[]) throws SocketException {
Enumeration nets =NetworkInterface.getNetworkInterfaces();for (NetworkInterfacenetint : Collections.list(nets))displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterfacenetint) throwsSocketException {out.printf("Display name: %s\n", netint.getDisplayName());out.printf("Name: %s\n", netint.getName());
EnumerationinetAddresses = netint.getInetAddresses();for (InetAddressinetAddress : Collections.list(inetAddresses)) {out.printf("InetAddress: %s\n", inetAddress);
}out.printf("\n");
}}The following is sample output from the example program:Display name: bge0Name: bge0InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2InetAddress: /121.153.225.59
http://java.sun.com/javase/7/docs/api/java/net/InterfaceAddress.htmlhttp://java.sun.com/javase/7/docs/api/java/net/InterfaceAddress.html7/27/2019 Java Networks Final
44/56
Display name: lo0Name: lo0InetAddress: /0:0:0:0:0:0:0:1%1InetAddress: /127.0.0.1
Network Interface Parameters
You can access network parameters about a network interface beyond the nameand IP addresses assigned to itYou candiscover if a network interface is up (that is, running) with the isUP()method. The following methods indicate the network interface type:
isLoopback() indicates if the network interface is a loopback interface. isPointToPoint() indicates if the interface is a point-to-point interface.
isVirtual() indicates if the interface is a virtual interface.
The supportsMulticast() method indicates whether the network interface supportsmulticasting. The getHardwareAddress() method returns the network interface'sphysical hardware address, usually called MAC address, when it is available.The getMTU() method returns the Maximum Transmission Unit (MTU), which isthe largest packet size.
The following example expands on the example in Listing Network InterfaceAddresses by adding the additional network parameters described on this page:
import java.io.*;import java.net.*;importjava.util.*;import staticjava.lang.System.out;
public class ListNetsEx{public static void main(String args[]) throws SocketException {
Enumeration nets =NetworkInterface.getNetworkInterfaces();
for (NetworkInterfacenetint : Collections.list(nets))displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throwsSocketException {out.printf("Display name: %s\n", netint.getDisplayName());
http://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/nifs/listing.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/nifs/listing.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/nifs/listing.htmlhttp://var/www/apps/conversion/tmp/tutorial-2010_01_12/tutorial/networking/nifs/listing.html7/27/2019 Java Networks Final
45/56
out.printf("Name: %s\n", netint.getName());EnumerationinetAddresses = netint.getInetAddresses();
for (InetAddressinetAddress : Collections.list(inetAddresses)) {out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("Up? %s\n", netint.isUp());out.printf("Loopback? %s\n", netint.isLoopback());out.printf("PointToPoint? %s\n", netint.isPointToPoint());out.printf("Supports multicast? %s\n", netint.supportsMulticast());out.printf("Virtual? %s\n", netint.isVirtual());out.printf("Hardware address: %s\n",
Arrays.toString(netint.getHardwareAddress()));out.printf("MTU: %s\n", netint.getMTU());
out.printf("\n");
}}The following is sample output from the example program:Display name: bge0Name: bge0InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2InetAddress: /129.156.225.59
Up? trueLoopback?falsePointToPoint?falseSupports multicast? falseVirtual?falseHardware address: [0, 3, 4, 5, 6, 7]MTU: 1500
Display name: lo0Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1InetAddress: /127.0.0.1Up? trueLoopback?truePointToPoint?falseSupports multicast? falseVirtual?falseHardware address: null
7/27/2019 Java Networks Final
46/56
MTU: 8232
Cookies
A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is apiece oftext stored by a user's web browser. A cookie can be used forauthentication, storing site preferences, shopping cart contents, the identifier fora server-based session, or anything else that can be accomplished throughstoring text data.
A cookie consists of one or more name-value pairs containing bits of information,which may be encrypted forinformation privacy and data security purposes. Thecookie is sent as an HTTPheaderby a web serverto a web browserand thensent back unchanged by the browser each time it accesses that server.Cookies, as with a cache, can be cleared to restore file storage space. If notmanually deleted by the user, cookies usually have an expiration date associatedwith them (established by the server that set it). Once that date has passed, thecookies stored by the client will automatically be deleted.
As text, cookies are not executable. Because they are not executed, they cannotreplicate themselves and are not viruses. However, due to the browsermechanism to set and read cookies, they can be used as spyware. Anti-spywareproducts may warn users about some cookies because cookies can be used totrack peoplea privacy concern, later causing possible malware.Most modern browsers allow users to decide whether to accept cookies, and the
time frame to keep them, but rejecting cookies makes some websites unusable.
Uses
Session management
Cookies may be used to maintain data related to the user during navigation,possibly across multiple visits. Cookies were introduced to provide a way toimplement a "shopping cart" (or "shopping basket"),[2][3] a virtual device intowhich users can store items they want to purchase as they navigate throughout
the site.
Shopping basket applications today usually store the list of basket contents in adatabase on the server side, rather than storing basket items in the cookie itself.
A web server typically sends a cookie containing a unique session identifier. Theweb browser will send back that session identifier with each subsequent requestand shopping basket items are stored associated with a unique session identifier.
http://en.wikipedia.org/wiki/Text_stringhttp://en.wikipedia.org/wiki/User_(computing)http://en.wikipedia.org/wiki/Web_browserhttp://en.wikipedia.org/wiki/Authenticationhttp://en.wikipedia.org/wiki/Shopping_cart_softwarehttp://en.wikipedia.org/wiki/Http_sessionhttp://en.wikipedia.org/wiki/Attribute-value_pairhttp://en.wikipedia.org/wiki/Encryptionhttp://en.wikipedia.org/wiki/Information_privacyhttp://en.wikipedia.org/wiki/Data_securityhttp://en.wikipedia.org/wiki/Hypertext_Transfer_Protocolhttp://en.wikipedia.org/wiki/HTTP_headerhttp://en.wikipedia.org/wiki/Web_serverhttp://en.wikipedia.org/wiki/Web_browserhttp://en.wikipedia.org/wiki/Cachehttp://en.wikipedia.org/wiki/Executablehttp://en.wikipedia.org/wiki/Computer_virushttp://en.wikipedia.org/wiki/Spywarehttp://en.wikipedia.org/wiki/Malwarehttp://en.wikipedia.org/wiki/Shopping_cart_softwarehttp://en.wikipedia.org/wiki/HTTP_cookie#cite_note-ks-1http://en.wikipedia.org/wiki/HTTP_cookie#cite_note-ks-1http://en.wikipedia.org/wiki/HTTP_cookie#cite_note-kristol-2http://en.wikipedia.org/wiki/HTTP_cookie#cite_note-kristol-2http://en.wikipedia.org/wiki/Unique_identifierhttp://en.wikipedia.org/wiki/Text_stringhttp://en.wikipedia.org/wiki/User_(computing)http://en.wikipedia.org/wiki/Web_browserhttp://en.wikipedia.org/wiki/Authenticationhttp://en.wikipedia.org/wiki/Shopping_cart_softwarehttp://en.wikipedia.org/wiki/Http_sessionhttp://en.wikipedia.org/wiki/Attribute-value_pairhttp://en.wikipedia.org/wiki/Encryptionhttp://en.wikipedia.org/wiki/Information_privacyhttp://en.wikipedia.org/wiki/Data_securityhttp://en.wikipedia.org/wiki/Hypertext_Transfer_Protocolhttp://en.wikipedia.org/wiki/HTTP_headerhttp://en.wikipedia.org/wiki/Web_serverhttp://en.wikipedia.org/wiki/Web_browserhttp://en.wikipedia.org/wiki/Cachehttp://en.wikipedia.org/wiki/Executablehttp://en.wikipedia.org/wiki/Computer_virushttp://en.wikipedia.org/wiki/Spywarehttp://en.wikipedia.org/wiki/Malwarehttp://en.wikipedia.org/wiki/Shopping_cart_softwarehttp://en.wikipedia.org/wiki/HTTP_cookie#cite_note-ks-1http://en.wikipedia.org/wiki/HTTP_cookie#cite_note-kristol-2http://en.wikipedia.org/wiki/Unique_identifier7/27/2019 Java Networks Final
47/56
Allowing users to log in to a website is a frequent use of cookies. Typically theweb server will first send a cookie containing a unique session identifier. Usersthen submit their credentials and the web application authenticates the sessionand allows the user access to services.
Personalization
Cookies may be used to remember the information about the user who hasvisited a website in order to show relevant content in the future. For example aweb server may send a cookie containingthe username last used to log in to aweb site so that it may be filled in for future visits.
Many websites use cookies forpersonalization based on users' preferences.Users select their preferences by entering them in a web form and submitting theform to the server. The server encodes the preferences in a cookie and sends
the cookie back to the browser. This way, every time the user accesses a page,the server is also sent the cookie where the preferences are stored, and canpersonalize the page according to the user preferences. For example, theWikipedia website allows authenticated users to choose the webpage skin theylike best; the Google search engine allows users (even non-registered ones) todecide how many search results per page they want to see.
Tracking
Tracking cookies may be used to track internet users' web browsing habits. Thiscan also be done in part by using the IP address of the computer requesting thepage or the referrerfield of the HTTP header, but cookies allow for a greaterprecision. This can be done for example as follows:
If the user requests a page of the site, but the request contains no cookie, theserver presumes that this is the first page visited by the user; the server createsa random string and sends it as a cookie back to the browser together with therequested page;
From this point on, the cookie will be automatically sent by the browser to theserver every time a new page from the site is requested; the server sends the
page as usual, but also stores the URL of the requested page, the date/time ofthe request, and the cookie in a log file.
By looking at the log file, it is then possible to find out which pages the user hasvisited and in what sequence. For example, if the log contains some requestsdone using the cookie id=abc, it can be determined that these requests all come
http://en.wikipedia.org/wiki/Personalizationhttp://en.wikipedia.org/wiki/Wikipediahttp://en.wikipedia.org/wiki/Skin_(computing)http://en.wikipedia.org/wiki/Googlehttp://en.wikipedia.org/wiki/IP_addresshttp://en.wikipedia.org/wiki/HTTP_referrerhttp://en.wikipedia.org/wiki/HyperText_Transfer_Protocolhttp://en.wikipedia.org/wiki/Personalizationhttp://en.wikipedia.org/wiki/Wikipediahttp://en.wikipedia.org/wiki/Skin_(computing)http://en.wikipedia.org/wiki/Googlehttp://en.wikipedia.org/wiki/IP_addresshttp://en.wikipedia.org/wiki/HTTP_referrerhttp://en.wikipedia.org/wiki/HyperText_Transfer_Protocol7/27/2019 Java Networks Final
48/56
from the same user. The URL and date/time stored with the cookie allows forfinding out which pages the user has visited, and at what time.
Third-party cookies and Web bugs, explained below, also allow for trackingacross multiple sites. Tracking within a site is typically used to produce usage
statistics, while tracking across sites is typically used by advertising companies toproduce anonymous user profiles (which are then used to determine whatadvertisements should be shown to the user).
A tracking cookie may potentially infringe upon the user's privacy but they can beeasily removed. Current versions of popular web browsers include options todelete 'persistent' cookies when the application is closed.
Third-party cookies
When viewing a Web page, images or other objects contained within this pagemay reside on servers besides just the URL shown in your browser. Whilerendering the page, the browser downloads all these objects. Most modernwebsites that you view contain information from lots of different sources. Forexample, if you type www.domain.com into your browser, widgets andadvertisements within this page are often served from a different domain source.While this information is being retrieved, some of these sources may set cookiesin your browser. First-party cookies are cookies that are set by the same domainthat is in your browser's address bar. Third-party cookies are cookies being setby one of these widgets or other inserts coming from a different domain.
The standards for cookies, RFC 2109 and RFC 2965, specify that browsersshould protect user privacy and not allow third-party cookies by default. But mostbrowsers, such as Mozilla Firefox, Internet Explorerand Opera, do allow third-party cookies by default, though they allow users to block them. Some Internetusers disable them because they can be used to track a user browsing from onewebsite to another. This tracking is most often done by on-line advertisingcompanies to assist in targeting advertisements. For example: Suppose a uservisits www.domain1.com and an advertiser sets a cookie in the user's browser,and then the user later visits www.domain2.com. If the same company advertiseson both sites, the advertiser knows that this particular user who is now viewing
www.domain2.com also viewed www.domain1.com in the past and may thusmore effectively target the user's interests or avoid repeating advertisements.The advertiser can then build up profiles on users.
http://en.wikipedia.org/wiki/Web_bughttp://tools.ietf.org/html/rfc2109http://tools.ietf.org/html/rfc2965http://en.wikipedia.org/wiki/Mozilla_Firefoxhttp://en.wikipedia.org/wiki/Internet_Explorerhttp://en.wikipedia.org/wiki/Opera_(web_browser)http://en.wikipedia.org/wiki/Web_bughttp://tools.ietf.org/html/rfc2109http://tools.ietf.org/html/rfc2965http://en.wikipedia.org/wiki/Mozilla_Firefoxhttp://en.wikipedia.org/wiki/Internet_Explorerhttp://en.wikipedia.org/wiki/Opera_(web_browse