Network Programming
Network Programming
Network Programming
Introduction to
Network Programming
What is Network programming?
• Features
• allows applications to connect and communicate via network.
• Read files from the internet and post files to the remote applications
via internet.
• Bash – language for Unix based system, very short and simple programs
• Java – OOP with rich sets of API, has a core library that includes classes
for communicating with the internet hosts, Java fills over 90% of most
• The course of network programming is based on Java.
• Example: FTP
• To achieve this peers can act as a client sometimes and as a server other
times.
Unit 2
Internet
Addresses
1. Internet Addresses:
Introduction
• Devices connected to internet are called nodes.
• Faster access
• ServerSocket
• URL
• DatagramSocket
3. Creating InetAddresses
• No public constructors in the InetAddress class.
where, obj = some object name & someMethod = a method of the InetAddress
class
• InetAddress me = InetAddress.getLocalHost();
• Can create addresses for hosts that donot exist or cannot be resolved.
• public static InetAddress getByAddress(byte[] addr) throws UnknownHostException
• The first method creates an InetAddress object with an IP address and no hostname
InetAddress lessWrongWithname =
InetAddress.getByAddress( "lesswrong.com", address);
How can you create InetAddress objects?
Method Description
static InetAddress getLocalHost() throws This method returns the instance of InetAddress
UnknownHostException containing the local hostname and address.
public static InetAddress getByName( String This method returns the instance of InetAddress
host ) throws UnknownHostException containing LocalHost IP and name.
static InetAddress[] getAllByName( String This method returns the array of the instance of
hostName ) throws UnknownHostException InetAddress class which contains IP addresses.
static InetAddress getByAddress( byte This method returns an InetAddress object created
IPAddress[] ) throws UnknownHostException from the raw IP address.
• The getHostname() method returns a string that contains the name of the host
with the IP address represented by this InetAddress object.
• If the machine does not have hostname or any other problems are found,simply the dotted
quad form of the IP address is returned.
• The getCanonicalHostName() method is similar to getHostName() but the
getCanonicalHostName calls the DNS in any case and may replace the
existing cached hostname.
• import java.net.*;
public class AddressTests {
public static int getVersion(InetAddress ia) {
byte[] address = ia.getAddress();
if (address.length == 4) return 4;
else if (address.length == 16) return 6;
else return -1;
}
}
Class Lab 2
• Illustrate the use of all the Getter methods using any suitable example. You can
choose any suitable InetAddress objects.
5. Address
Types
• Some IP addresses and some patterns of address have special meanings.
• 127.0.0.1 is loopback address
• 224.0.0.0 to 239.255.255.255 are multicast addresses
• Java includes 10 methods for testing whether an InetAddress object meets any of these criteria.
• Connections can be blocked for many reasons including fiurewalls, proxy srevers,
misbehaving routes, broken cables or if the remote host is turned off.
• public boolean isReachable(int timeout) throws IOException
public boolean isReachable(NetworkInterface interface, int ttl, int timeout) throws IOException
• In first method of if the host responds within the timeout, true is returned else false.
• The second allows you to specify le local network interface and Time-to-Live.
7. Object Methods
• Like every other class InetAddress inherits from java.lang.Object.
• Hence it has access to all the methods of that class and overrides three methods.
• public boolean equals(Object o)
public int hashCode()
public String toString()
• The hashCode() method is similar to equals() method. The integer that hashCode()
returns is calculated solely from the IP address. If addresses are same then they
have same hash code even if hostnames are different.
• The toString() method returns short text representation of the
object.
• Class Lab 4
• Even if we need to know then, it is quicker to check the size of byte array using getAddress()
method.
• It returns true if and only if the address is essentially an IPv4 address stuffed into an IPv6
container. That is, the address has the form 0:0:0:0:0:0:0:xxxx.
9. The Network Interface
Class:
• The NetworkInterface class represents a local IP address.
• Then these InetAddress objects can then be used to create sockets, server
sockets and so on.
9. The Network Interface Class: Factory
Methods
• Since NetworkInterface objects represent physical hardware and virtual
addresses, they cannot be constructed arbitrarily.
• Like the InetAddress class, there are static factory methods that return the
NetworkInterface object associated with a particular network interface.
Example:
NetworkInterface ni = NetworkInterface.getByName("eth0");
public static NetworkInterface getByInetAddress(InetAddress address)
throws SocketException
• throws SocketException.
• InetAddress local = InetAddress.getByName("127.0.0.1");
NetworkInterface ni = NetworkInterface.getByInetAddress(local);
public static Enumeration getNetworkInterfaces() throws
SocketException
• The getNetworkInterfaces() method returns a java.util.Enumeration listing all
the
network interfaces on the local host.
• The Enumeration interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects.
Enumeration interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{ System.out.println(interfaces.nextElement(
));
10. The NetworkInterface Class: Getter
•Methods
Once you have NetworkInterface object, you can inquire about its IP address
and
name.
• To find out if a certain IP address is a known spammer, reverse the bytes of the
address, add the domain of the blackhole service, and look it up. If the address is
found, it’s a spammer. If it isn’t, it’s not
• If the DNS query succeeds (and, more specifically, if it returns the address 127.0.0.2),
then the host is known to be a spammer. If the lookup fails—that is, it throws an
UnknownHostException.
Processing Web Server Logfiles
• Web server logs track the hosts that access a website.
• The log reports the IP addresses of the sites that connect to the server.
• Most web servers have an option to store hostnames instead of IP addresses, but this
can
hurt performance because the server needs to make a DNS request for each hit.
• It is much more efficient to log the IP addresses and convert them to hostnames at
a later time, when the server isn’t busy.
• Such program is called Weblog that reads a web server logfile and prints each line
with IP address converted to hostnames.
• Go through the Lab Manual for Programs of SpamCheck and WebServer Log
files.
Unit 3
URLs and URIs
Instructor:
Manoj
Pokharel
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 1
Background
• Unit 2: learned how to address hosts on the internet via hostname and
IP address.
• The URL class is the simplest way for a Java program to locate and
retrieve data from the network.
Class labs, programs and Related Java Code can be downloaded from:
HERE!!! Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 2
3.1. URIs: URLs and Relative URLs
• URI Syntax:
• scheme:scheme-specific-part
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 5
Some examples of URI
• http://www.ietf.org/rfc/rfc3986.txt
• Scheme: http
• Authority: www.ietf.org
• Path: frc/rfc3986.txt
• Query: Not specified
• Implies that the server at www.ietf.org is responsible for mapping the path
frc/rfc3986.txt to a resource
• http://www.powells.com/cgibin/biblio?inkey=62-1565928709-0
• ftp://mp3:[email protected]:33/VanHalen-Jump.mp3
• mailto:[email protected]
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 6
URLs
• URL is a URI it identifies a resource and also helps client retrieve that
resource.
• port (optional):
• Most of this information is likely to be same for other URLs that are
referenced in the document.
• In a relative URL any pieces that are missing are assumed to be same as the
corresponding pieces of absolute URL.
• suppose you are browsing: http://www.ibiblio.org/javafaq/java‐tutorial.html and click on
the hyperlink <a href="javafaq.html">
try {
URL u = new URL("http://www.audubon.org/");
} catch (MalformedURLException ex) {
System.err.println(ex);}
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 11
Constructing a URL from its component parts
• You can build a URL by specifying the protocol, the hostname and the file.
• Code:
try {
URL u = new URL("http", "www.eff.org", "/blueribbon.html#intro");
} catch (MalformedURLException ex) {
• This constructor uses default port, file argument should begin with a slash and
include a path, a filename.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 12
• In rare cases, the default port may not be used.. The next constructor lets you
specify the port explicitly as an int data type. The other arguments are same.
try {
URL u = new URL("http", "fourier.dur.ac.uk", 8000, "/~dma3mjh/jsci/");
} catch (MalformedURLException ex) {
throw new RuntimeException("shouldn't happen; all VMs recognize http");
}
• For example, this code fragment creates a URL object that points to
http://fourier.dur.ac.uk:8000/ ~dma3mjh/jsci/, specifying port 8000 explicitly
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 13
Constructing relative URLs
• The constructor builds an absolute URL from relative URL and a base
URL.
• public URL(URL base, String relative) throws MalformedURLException
try {
URL u1 = new URL("http://www.ibiblio.org/javafaq/index.html");
URL u2 = new URL (u1, "mailinglists.html");
} catch (MalformedURLException ex) {
System.err.println(ex);}
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 15
3.2.2 Retrieving Data From a URL
• The URL class has several methods that retrieve data from a URL.
• public InputStream openStream() throws IOException
public URLConnection openConnection() throws IOException
public Object getContent() throws IOException
public Object getContent(Class[] classes) throws IOException
• And then you can ask the URL for its content with getContent(() which
may give you a more complete object such as String or an Image.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 16
Public final InputStream openStream() throws IOException
• The openStream() method connects to the resource referenced by the
URL, and returns an InputStream from which data can be read.
• The data you get from InputStream is the raw content of URL
references.
• The code shows how to connect to a resource and read the data from
the resource using InputStream.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 17
InputStream in = null
try {
URL u = new URL("ht
tp://www.lolcats.co
m
");
in = u.openStream();
int c;
while ((c =
in.read()) != -1)
System.out.write(c);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) { Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 18
Class Lab 1
• Write a program to download a web page using the URL of the web
page. Use the openStream and InputStreamReader’s read()
method.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 19
public URLConnection openConnection() throws IOException
• OpenConnection() method opens a socket to the specified URL and
returns a URLConnection object.
• Use this method when you wish to communicate directly with the server
• It also allows you to write data to as well as the read from a URL. (Send
email, POST to server)
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 20
try {
URL u = new URL("https://news.ycombinator.com/");
try {
URLConnection uc = u.openConnection();
InputStream in = uc.getInputStream();
// read from the connection...
} catch (IOException ex) {
System.err.println(ex);
}
} catch (MalformedURLException ex) {
System.err.println(ex);
}
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 21
public final Object getContent() throws IOException
• 3rd way to download data referenced by a URL.
• If URL refers to some kind of text such as an ASCII or HTML file, the object returned is
some sort of InputStream.
• If URL refers to an image such as a GIF or a JPEG, it returns java.awt.ImageProducer
• General syntax:
// work with the OCobmjpeeli cdtb.y.: .Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 22
Class Lab 2: A program to download an object specified by
URL
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 23
Public final Object getContent(Class[] classes) throws IOException
• The method attempts to return the URLs content in the first available
format.
• If you prefer an HTML file to be returned as a String, but your
second choice is a Reader and 3rd choice is an InputStream, write the
code as:
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 24
URL u = new URL("http://www.nwu.org");
Class<?>[] types = new Class[3];
types[0] = String.class;
types[1] = Reader.class;
types[2] = InputStream.class;
Object o = u.getContent(types);
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 25
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof
Reader) {
int c;
Reader r = (Reader) o;
while ((c = r.read()) != -1) System.out.print((char) c);
r.close();
} else if (o instanceof InputStream) {
int c;
InputStream in = (InputStream) o;
while ((c = in.read()) != -1) System.out.write(c);
in.close();
} else {
System.out.println("Error: unexpected type " +
o.getClass()); Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 26
3.2.3 Splitting a URL into pieces
• URLs are composed of five pieces:
• The scheme, also known as the protocol
• The authority
• The path
• The fragment identifier, also known as the section or ref
• The query string
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 27
• For example, in the URL
http://www.ibiblio.org/javafaq/books/jnp/index.html?isbn=1565922069#toc, the
scheme is http, the authority is www.ibiblio.org, the path is /
javafaq/books/jnp/index.html, the fragment identifier is toc, and the query string is
isbn=1565922069. However, not all URLs have all these pieces. For instance, the
URL http://www.faqs.org/rfcs/rfc3986.html has a scheme, an authority, and a path,
but no fragment identifier or query string.
• The authority may further be divided into the user info, the host, and the port.
For example, in the URL http://[email protected]:8080/, the authority
is [email protected]:8080. This has the user info admin, the host
www.black‐star.com, and the port 8080
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 28
• Read-only access to these parts of a URL is provided by nine public
methods:
• getFile(), getHost(), getPort(), getProtocol(), getRef(),
getQuery(), getPath(), getUserInfo(), and getAuthority()
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 29
• public String getProtocol() : returns a string containing the scheme of the
protocol. (http, file, https). Code fragment looks like this:
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 30
• public int getPort(): returns the port number specified in the URL as an int.
• If no port is specified it returns -1 (denotes use of default port)
• public int getDefaultPort(): returns the default port used for this URL’s
protocol when none is specified in the URL.
• If no default port is defined for the protocol, then getDefaultPort() returns -
1. For example, if the URL is http://www.userfriendly.org/, getDefaultPort()
returns 80; if the URL is ftp://ftp.userfriendly.org:8000/, getDefaultPort()
returns ????? Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 31
• public String getFile(): returns String that contains the path portion of the
URL. Everything from the first slash (/) after the hostname until the character
preceding the # sign is considered to be part of file.
• public String getRef(): returns the fragment identifier part of the URL. If the
URL doesn’t have a fragment identifier, the method returns null.
• public String getAuthority(): returns the authority that resolves the resource.
• in the URL http://conferences.oreilly.com/java/speakers/, the authority is simply the
hostname conferences.oreilly.com.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 33
Class Lab 3: Write Java code to accept a URL as user input and split the
URL into pieces.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 34
3.2.4 Equality & Comparison and Conversion
• The URL class contains the usual equals() and hashCode() methods.
• Two URLs are considered equal if and only if: both URLs point to the same
resource on the same host, port and path within the same fragment and query
string.
• equals() works with DNS, hence, http://www.google.com and
http://google.com are same. But http://www.google.com:80 is not equal to
http://www.google.com
• Also, http://chpl.com/index.html and http://chpl.com are not same same since it
does not compare the resources identified by two URLs.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 35
Class Lab: Write Java code to check either http://www.ibiblio.org and
http://ibiblio.org are same or not?
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 36
Conversion
• URL has three methods that convert an instance to another form: toString(),
toExternalForm(), and toURI()
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 37
URL vs URI classes
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 38
3.3 The URI Class:
• A Uniform Resource Identifier consists of both URLs and URIs.
https://stackoverflow.com/questions/4913343/what-is-the-difference-between-uri-
url-and-urn -
• Use the URL class when you want to download the content at a URL and the
URI class when you want to use the URL for identification rather than retrieval
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 39
3.3.1 Constructing a URI
• URIs are built from strings. You can either pass the entire URI to the constructor
as a single string or the individual pieces.
public URI(String uri) throws URISyntaxException
public URI(String scheme, String schemeSpecificPart, String fragment) throws
URISyntaxException
public URI(String scheme, String host, String path, String fragment) throws
URISyntaxException
public URI(String scheme, String authority, String path, String query,String fragment)
throws URISyntaxException
public URI(String scheme, String userInfo, String host, int port,String path, String query,
String fragment) throws URISyntaxException
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 40
• As long as the syntax is correct for URI, an URI object can be created.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Net. Programming, 2014 41
3.3.2 The Parts of the URI
• A URI reference has up to three parts: a scheme, a scheme-specific part, and a
fragment identifier. The general format is: scheme:scheme-specific-part:fragment
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 44
3.3.3 Resolving Relative URIs
• URI class has three methods for converting back and forth between
relative and absolute URIs.
• public URI resolve(URI uri)
public URI resolve(String uri)
public URI relativize(URI uri)
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 47
3.4 x-www-form-urlencoded: URLEncoder and URLDecoder
• Major problem for web designers is to deal with difference between
operating systems.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 48
• Hence characters used in URLs must come from a fixed subset of
ASCII, specifically:
• The capital letters A-Z
• The lowercase letters a-z
• The digits 0-9
• The punctuation characters -_.!~* and so on
• The characters : / & ? @ # ; $ + = and % may also be used, but only for their
specified purposes. If these characters occur as part of a path or query string, they
and all other characters should be encoded.
• Encoding is simple; Any characters that are not ASCII numerals, letters or
punctuation characters are converted into bytes and each byte is written as a percent
sign followed by two
Compiled hexadecimal
by: Manoj Pokharel @Nepathyadigits
College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 49
• Spaces are encoded as %20 and sometimes +
• The / # = & and ? Must be encoded when they are used as part of name,
not as a separator between parts of the URL.
• URL class does not encode or decode automatically. You construct URL
objects that use illegal ASCII and non-ASCII characters and then use
the Java URLEncoder and URLDecoder classes to perform encoding
and decoding
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 50
URLEncoder
• To encode a string, pass the string and the character set name to the
URLEncoder.encode() method. For example:
• Although this method allows you to specify the character set, the only
such characterCompiled
set by:you should ever pick is UTF-8
Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 51
Class Lab 5: Show how the punctuation characters space, *, %, +, \, :, =, & are
encoded using the encode() method.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 52
URLDecoder
• The URLDecoder class has a static decode() method that decodes string
encoded in x-www-form-url-encoded format.
• It converts all plus signs to spaces and all percent escapes to their
corresponding character.
• You can simply pass an entire encoded URL rather then splitting it into
pieces first. The previously encoded string can be decoded as:
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 54
3.5 Proxies: System Properties, The ProxyClass and The ProxySelector
• Many systems access the WWW and Internet through proxy servers.
• A proxy server receives request from local clients and forwards to the
remote server, receives response from remote server and sends to client.
• Java programs based on the URL class can work with most proxy servers
and protocols.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 55
3.5.1 System Properties
• For basic operations, you have to set few system properties to point to the
addresses of your local proxy servers.
• For pure HTTP proxy: set http.proxyHost to the domain name or the IP
address of proxy server and http.proxyPort to the port of the proxy
server.
• The http.nonProxyHosts excludes the host from using the proxy server. i.e.
a direct connection is established with the specified host.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 57
• Wildcard * can be used to indicate all hosts within a particular domain
that should not be proxied.
• System.setProperty("http.nonProxyHosts", *.oreilly.com");
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 58
3.5.2 The Proxy Class
• Manually choosing the proxy type and defining it manually as system
properties is not feasible.
• Hence we use the Proxy class, it allows more fine grained control of
proxy servers.
• To be specific, it allows you to choose different proxy servers for
different remote hosts.
• Proxy servers are represented by instances of the Proxy class and three
kinds of proxies do exist.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 59
• Three proxies are: HTTP, SOCKS and DIRECT each represented as
three constants in the Proxy.Type enum:
• Proxy.Type.DIRECT
• Proxy.Type.HTTP
• Proxy.Type.SOCKS
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 60
3.6 Communicating with Server-Side programs through GET
• Then we can construct a URL with query string that provides the
names and values. The names and values must be x-www-form-
url- encoded using the URLEncoder.encode() method.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 61
Additional Info:
• Self written server side program => you already know the name value pairs
However, many programs are designed to process form input. In this case it is
easy to figure out what input the program excepts.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 62
• The method the form uses should be the value of ‘method’ attribute
of the ‘form’ element. Method can be GET or POST. We deal with
GET.
• The part of the URL before the query string is given by the value of
‘action’ attribute of the form element.
• Consider an example:
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 63
Additional Info:
<form name="search" action="http://www.google.com/search" method="get">
<input name="q" />
<input type=“text" value="cafe.org" name="domains" />
<input type=“text" name="sitesearch" value="cafeconleche.org" />
<input type=“text" name="sitesearch2" value="cafeconleche.org" />
<br />
<input type="image" height="22" width="55"
src="images/search_blue.gif" alt="search" border="0“
name="search-image" />
</form>
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 64
• After you determine the name value pairs the server side program
expects, communicating with it is simple:
• To do so, we
• create a query string that includes the necessary name-value
pairs,
• Then form a URL that includes the query string
• Send the query string to the server
• Use the methods studied earlier to retrieve a HTML page.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 68
3.7 Accessing Password-Protected Sites
• The URL class can access sites that use HTTP authentication once the
username and password is provided.
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 69
3.7.1 The Authenticator Class
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 70
• The syntax of the Authenticator class is:
• Then the member functions of the class can be used for authentication:
• getPasswordAuthentication()
• getRequesting Host()
• getRequestingPort
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 71
The PasswordAuthentication Class
• The class that processes two read-only attributes: username and password.
• The username and password stored in the class is accessed using the getter
methods: public String getUserName() and public char[] getPassword()
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 72
The JPasswordField Class
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 73
Compiled by: Manoj Pokharel @Nepathya College, Reference: E.R Harold, Java Network Programming,O’Reilly 2014 74
Unit 4 : HTTP
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
4.1 The Protocol:
HTTP
• Standard protocol for communication between web browsers and web servers.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
• Each HTTP request from client to server includes four steps:
• Client opens TCP connection to the server using the given port in URL
(default : 80)
• Client sends message to the server requesting the resource at the specified
path. Resource includes header.
• The server sends response to the client. The response includes a response
code followed by a header, and the requested document or an error message.
• The server closes the connection
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 3
•• EEaacchh rreeqquueesst aanndd rreessppoonnssee inn HHTTTTPP hhaass ssaammee bbaassicc foorrmm: aa hheeaaddeerr lliinnee,,
aann HHTTTTPP
header containing metadata, a blank line and then a message body.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
HTTP Keep-
Alive:
• HTTP version 1.0 opens a new connection for each request.
• In sessions where many small documents need to be transmitted, the time taken to
open and close connections is more than the time taken to transmit the data.
• The case seems more problematic for encrypted HTTPS connections using SSL
or TLS. (due to handshake required for secure socket)
• In HTTPS 1.1 and later, the server does not have to close the socket after it
sends response.
• i.e. it can leave the socket open and wait for a new request from the client on
the same socket.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
• A client indicates that it is willing to reuse the socket by including a Connection field in
the
HTTP request header with the value Keep-Alive.
• Connection: Keep-Alive
• The URL class supports HTTP Keep-Alive unless explicitly turned off. i.e. if the
client connects to the same server before the server has closed the connection, the
socket is reused.
• Each has their own semantics and usage corresponding to Read, Create,
Update, Delete (CRUD)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 th edition, Elliotte Rusty Harold 7
GET Method:
• This method is used to read (retrieve) a representation of a resource.
• In case of error, it often returns a code 404 (NOT FOUND) or 400 (BAD
REQUEST)
• HTTP GET methods are considered safe. i.e. they can be used without any risk
of data
modification or corruption.
• Calling it once and calling it multiple times has no any effect on data
modificationCompiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 edition, Elliotte Rusty Harold
th 8
POST Method
• POST method is most often utilized to create new resources.
• POST is not safe operation. i.e. making two identical POST request will result
in two resources containing the same information but with different identifiers.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
PUT Method
• The PUT method uploads a representation of a resource to the server at a
known URL.
• It is not side effect free but idempotent. i.e. executing the same identical
request multiple times leaves the server in the same state. (No any effect)
DELETE Method:
• The DELETE request is used to delete a resource identified by the URL.
• Deleting the same resource multiple times has no effect on state of data.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 10
4.3 The Request
Body
• Format of the request body for HTTP methods
• POST and PUT: in these cases, the client supplies the representation of the
resource along with the path and the query string.
• The representation is sent in the body of the request, after the header.
• An HTTP header
• A blank line
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
• The HTTP header should include two fields that specify the nature of the body.
• A Content-length field that specifies how many bytes are in the body.
• A Content-type field that specifies the MIME media type of the bytes.
• For Example in previous slide. The request body is of 54 bytes and the media
type is (application/x-www-form-urlencoded)
• However other media types can also be defined, a picture can be uploaded
as image/jpeg, text editors might send text/html.
• Note: MIME = Multipurpose Internet Mail Extensions, specifies the content type or media
on Internet
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
• Example, a PUT request that uploads an Atom
document:
PUT /blog/software-development/the-power-of-pomodoros/ HTTP/1.1
Host: elharo.com
User-Agent: AtomMaker/1.0
Authorization: Basic ZGFmZnk6c2VjZXJldA==
Content-Type: application/atom+xml;type=entry
Content-Length: 322
<?xml version="1.0"?>
<entry xmlns="http://www
.w3.org/2005/Atom">
<title>The Power of Pomodoros</title>
<id>urn:uuid:101a41a6-722b-4d9b-8afb-
ccfb01d77499</id>
<updated>2013-02-22T19:40:52Z</updated>
</entry> Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 th edition, Elliotte Rusty Harold 14
<author><name>Elliotte
Cookies
• Many websites use small strings of text known as cookies to store persistent
client-side state between connections.
• Cookies are passed from server to client and back again in the HTTP headers
of requests and responses.
• Cookies are used by server to indicate session IDs, login credentials, shopping
cart
details, user preferences etc.
• Cookies actually do not store the data but point to the data stored in server.
• Cookies are limited to non-whitespace ASCII text, and doesnot contain commas
or semicolons.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 th edition, Elliotte Rusty Harold 15
• To set a cookie in a browser, the server includes a Set-Cookie header line in the
HTTP header.
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: cart=ATVPDKIKX0DER
• If the browser makes a second request to the same server, it will send the
cookie back in Cookie line in the HTTP request header like:
• In addition to a name = value pair , cookies can have other attributes that control
their scope including expiration date, path, domain, port, version and security
options. Example; cookie for subdomians,
• Set-Cookie: user=elharo;Domain=.foo.example.com
• These two lines of code allow Java to store any cookies sent by HTTP servers
that you connect to by using the URL class.
• It will also send the stored cookies back to those servers in subsequent requests.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 18
• Further, you can specify which and whose cookies to accept using the
CookiePolicy. The policies are fixed and predefined:
• CookiePolicy.ACCEPT_ALL All cookies allowed
• Example to block third party cookies but accept 1st party cookies.
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
CookieHandler.setDefault(manager);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
CookieStore
• In cases when cookies are necessary for manipulation locally, one can get the cookies stored in the disk
using the CookieStore.
• You can retrieve the cookies stored by the CookieManager using the getCookieStore() method.
• The CookieStore class allows to add remove and list the cookies. Following methods can be used:
1
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
URLConnection
• Abstract class that represents an active connection to a resource specified by
a URL.
• Many of the methods and fields including the constructor in the class are
protected.
• Can only be accessed by the instances of the class or its subclasses.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
5.1 Opening URLConnections
• A program can open connection to a URL following basic sequence of
steps:
1. Construct a URL object
try {
URL u = new URL("http://www.overcomingbias.com/");
URLConnection uc = u.openConnection();
// read from the URL...
} catch (MalformedURLException ex) {
System.err.println(ex);
} catch (IOException ex)
{ System.err.println(ex);}
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
5.2 Reading Data from a
Server
•The steps needed to retrieve data from a URL using a
URLConnection object are:
1. Construct a URL object
• URLConnection can both read data from server and write data to server.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 7
5.3 Reading Header:
• HTTP servers provide plenty of information in the header that precedes
each response. See an sample header returned by an Apache web
server:
HTTP/1.1 301 Moved Permanently
Date: Sun, 21 Apr 2013 15:12:46 GMT
Server: Apache
Location:
http://www.ibiblio.org/ Content-
Length: 296
Connection: close
Content-Type: Compiled
text/html;
by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
• HTTP header may include:
• The content type of the requested document
• Here we deal with finding the metadata that server has provided and
retrieving the header fields.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
5.3.1Retrieving Specific Header
Fields
• There exist several methods that can be used to extract fields from header:
fields can be specific or arbitrary.
• Following six methods can be used to extract common fields from the
header:
3. public String getContentEncoding() => returns a string that tells how the
content is encoded.
• If the content is unencoded (common in HTTP servers) this method returns null.
4. Public long getDate() => returns a long that tells you when the document
was sent, in milliseconds since midnight, GMT, January 1,1970
• Can be converted inti java.util.Date using Date docdate = new Date(uc.getDate());
• If header has no date field, it returns zero.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
5. public long getExpiration() => some documents come with expiration dates that
indicates when the document should be deleted from the cache and reloaded
from the server.
• Similar to getDate(), returns a long indicating the number of milliseconds after
12:00 AM,GMT Janauary 1, 1970 at which the document expires.
• If no expiry date specified, returns zero.
• (similar to above)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
5.3.2 Retrieving Arbitrary Header
• TheFields
previous six methods requested most common fields from the header.
• But there exist other header fields that a message can contain.
• The following five methods can be used to inspect these arbitrary fields:
• For example to get the sixth key of the header of the URLConnection object uc
the code becomes: String header6 = uc.getHeaderFieldKey(6);
3. public String getHeaderField(int n): returns the value of the nth header field.
• The starter line containing the request method and path is header field zero
• If it fails to parse int or cant find the header it returns the default
value.
• Example: to retrieve content-length field of the header fron
the URLConnection object uc, the code would be:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 17
5.4 Web Cache for Java
• Web browsers have been caching pages and images for years.
• By default, any web page accessed using GET method over HTTP can
be cached.
• A page accessed with HTTPS and POST usually need not be cached.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 18
• By default, Java does not cache anything.
• Once the cache is installed whenever a system tries to load new URL, it will
first look for it in the cache.
• If the content is found, cache returns the desired content and
the URLConnection wont need to connect to the remote server.
• If the desired content is not found, the data will be fetched from the server
and the data will be put in the cache
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
• Setting up the system-wide cache is done using the setDefault method:
• Two methods in the ResponseCache class store and retrieve data from the systems cache:
• public abstract CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders)
throws IOException
• The put() method returns a CacheRequest object that wraps an OutputStream into
which the URL will write cachable data it reads.
• The get() method in ResponseCache retrieves the data and headers from the cache
and returns then wrapped in CacheResponse object.
• If the desired URI is not in the cache, it returns null and URI is loaded form server.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 20
5.5 Configuring the
Connection:
• The URLConnection class has seven protected instance fields that define
exactly how the client makes request to the server.
protected URL url;
protected boolean doInput = true;
protected boolean doOutput = false;
protected boolean
allowUserInteraction =
defaultAllowUserInteraction;
protected boolean useCaches =
defaultUseCaches;
protected long ifModifiedSince = 0;
protected boolean connected =
false;
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 21
• The following getter/setter methods do exist:
public URL getURL()
public void setDoInput(boolean doInput)
public boolean getDoInput()
public void setDoOutput(boolean doOutput)
public boolean getDoOutput()
public void setAllowUserInteraction(boolean allowUserInteraction)
public boolean getAllowUserInteraction()
public void setUseCaches(boolean useCaches)
public boolean getUseCaches()
public void setIfModifiedSince(long
ifModifiedSince)
public long getIfModifiedSince()
• Getters and setters can be used to read and change its values
• True indicates that the user interaction is allowed , false indicates that user
interaction is not possible.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 24
• Example for allowUserInteraction:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 25
• Protected boolean doInput: A URLConnection can be used for reading
from a server, writing to a server, or both.
• The doInput field is true if the URLConnection can be used for reading,
false if it doesnot allow read.
• Getter and setter methods can be used to read the value and change the
value.
} uc.setDoOutput(true);
• The header includes a date and time. If the document has changed since that
time, the server should send it. Otherwise it replies with a 304 Not
Modified message.
• The client then loads the document from its cache.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 28
• protected boolean useCaches: Some web browsers can retrieve a document from local
cache, rather than retrieving it from server.
• The useCaches variable determines whether a cache will be used if its available.
• Default value is true, If the program/app does not wish to use cache set to false
• Timeouts: four methods query and modify the timeout values for connections that specifies
how long the socket will wait for remote host before throwing SocketTimeoutException.
• The ConnectTimeout() (get/set) method controls how long the socket waits for initial
connection.
• The ReadTimeout() (get/set) method specify how long the input stream waits for
data to arrive.
29
• If value = 0, indicates never timeout.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
• Example for useCaches
• try {
URL u = new URL("http://www.sourcebot.com/");
URLConnection uc = u.openConnection();
uc.setUseCaches(false); • Example for Timeouts
• URL u = new URL("ht
// read the document...
tp://www.example.org");
} catch (IOException ex) {
URLConnuction uc = u.openConnection();
System.err.println(ex); uc.setConnectTimeout(30000);
} uc.setReadTimeout(45000);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 30
5.6 Configuring the Client Request HTTP
Header
• A client using HTTP sends the data along with a request line and a header. Example:
GET /index.html HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101
Firefox/20.0 Host: en.wikipedia.org
Connection: keep-alive
Accept-Language: en-
US,en;q=0.5 Accept-Encoding:
gzip, deflate
Accept:
text/html,application/xhtml+xml,a
pplication/xml;q=0.9,*/*;q=0.8
• A web server can use this information to serve different pages to different clients, to get
and set cookies,Compiled
header authenticate users through passwords and more
by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 31
• Each URLConnection sets a number of different name-value pairs in the header by
default.
• However, you can modify these and add new fields before connecting.
This modification is referred as configuring the HTTP request header.
• It adds a field to the header of the URLConnection object with the specified name
and value.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 32
• HTTP allows single name to have multiple values. In this case the separate
values are separated by commas.
• Given a URLConnection object uc, the header field ‘Accept: text/html, image/gif,
image/jpeg’ can be set as follows:
• Before attempting to connect to a URL and reading and writing files, you
should confirm weather the connection will be allowed.
• This class provides additional methods that are helpful when working
specifically with the http URLs.
• Particularly, it has:
• Methods to get and set request method (GET, POST, PUT, DELETE)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 35
• You cannot directly create its object because it is an abstract class and
its only constructor is protected.
• OR
• Also clients can POST responses to forms, PUT files to server or DELETE
files form server, get HEADer of a document an so on.
• These tasks are accomplished by changing the request method in the request
line.
• However it is not enough to simply set the request method, you must adjust
the HTTP header and also provide a message body depending on the
header as well.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 38
• HEAD: method instructs the sever to return only the HTTP header, not the file.
• HEAD can be used to check either a resource has been modified since last time or not.
• try {
URL u = new URL(args[i]);
HttpURLConnection http = (HttpURLConnection) u.openConnection();
http.setRequestMethod("HEAD");
System.out.println(u + " was last modified at "
+ new Date(http.getLastModified()));
} catch
//Error handling}
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 39
• OPTIONS: The options method asks what options are supported for a particular
URL. For example, for the request
• OPTIONS /xml/ HTTP/1.1
Host: www.ibiblio.org
Accept: text/html, image/gif, image/jpeg
Connection: close
• It is mainly used to see what proxy server is changing in the clients request.
• If no proxy server is used, the Response:
HTTP/1.1 200 OK
part of the messages in red
Date: Sat, 04 May 2013 14:41:40 GMT
remain identical or else might Server: Apache
change. Connection: close
Request: Content-Type:
TRACE /xml/ HTTP/1.1 message/http
Hello: Push me TRACE /xml/ HTTP/1.1
Host: www.ibiblio.org Hello: Push me
Accept: text/html, image/gif, image/jpeg Host: www.ibiblio.org
Connection: close Accept: text/html, image/gif, image/jpeg
Connection: close
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 41
5.9.2 Disconnecting from the
Server
• HTTP 1.1 and later versions support persistent connections that allow
multiple requests and responses to be sent over a single TCP socket
using the Keep-Alive attribute.
• When the Keep-Alive attribute is used, the server wont close the connection
even all the bytes of the requested data is sent because servers expect that
the client may send further data.
• However servers will time out and close the connection in 5 seconds on
inactivity, it is preferred for the client to close the connection as soon as it
knows that its task is complete.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 42
• As every HTTP protocol, HttpURLConnection class transparently
supports HTTP Keep-alive unless explicitly turned off.
• Once you know you are done talking with the server, you can use
the disconnect() method to break the connection with the server.
• The disconnect() method closes all the streams that are open on the
specified connection(if any).
• However closing the stream on the persistent connection does not close the
socket and disconnect.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 43
5.9.3 Handling Server
Responses
•The Status line of an HTTP response includes a numeric code and
a message referred as response code and response message.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 44
5.9.4 Proxies
• Many users behind firewalls or other ISP’s access the Web through proxy
servers.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 45
5.9.5 Streaming Mode
• When you need to send and receive data Java caches everything that is fed
into the OutputStream retrieved from the HttpURLConnection until the
stream is closed.
• The scheme is fine for small requests such as form data. However it is not
good for large responses or other huge messages.
• It is very inefficient if you need to share large files since everything needs
to be cached.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 46
• First, if you know the size of data (if you are uploading the file of known
size using PUT)- you can tell the HttpURLConnection object the size of
data.
• Second, if you do not know the size, you can use chunked transfer.
• Chunk transfer the request body data is split into pieces and sent in multiple
pieces each with its own content length.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 47
End of Unit
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 48
Unit 6: Socket for Clients
1
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
6.1 Introduction to
•sockets
Data is transmitted as packets called datagrams.
• Header + Payload = Datagram
• Address + Port No. (both sender and receiver) + other details = Header
• Details = checksum (error detection), fragmentation info
• Keeping track of all these tasks and managing these is a tedious task.
• Hence sockets come in play,
• Socket allow a programmer to treat a network connection as a stream onto
which
the bytes can be written and read.
• Low level details such as error detection, packet sizes, fragmentation and
reassemblyCompiled
all are automatically
by Manoj handled
Pokharel@ Nepathya College, by sockets
Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
6.2 Using Sockets
• A socket is a connection between two hosts.
• Address + Port = Socket (Example)
• Close a connection
• Bind to a port
• The later three operations are applicable for server are provided by the
ServerSocket class.
• The connection then gets the input output streams from the socket and
use these streams to send and receive data to each other.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
• The connection is full duplex.
6.2.1 Investigating Protocols with Telnet
• Telnet provides a simple way that demonstrates how a protocol operates.
• the above command requests a connection to port 25, the SMTP port on
the local machine.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
6.2.2 Reading from Servers with
Sockets
• We will connect to the daytime server at the National Institute for Standards
and Technology (NIST) and fetch the current time.
• The server listens on port 13 and sends the UTC time in human readbale
format and closes the connection. Example:
• telnet time.nist.gov 13 returns 59659 22-03-21 05:53:07 50 0 0
881.9 UTC(NIST) *Connection to host lost.
• Now we use the InputStream() object to read bytes from the socket:
• InputStream in = socket.getInputStream();
StringBuilder time = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, "ASCII");
for (int c = reader.read(); c != -1; c = reader.read())
{ time.append((char) c);
}
7
System.out.prinCotmlnpi(letdibmy Mea)n;oj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty
• The overall program looks as follows:
public static void main(String[] args) {
String hostname = args.length > 0 ? args[0] : "time.nist.gov"; Socket socket = null;
try {
socket = new Socket(hostname, 13);
socket.setSoTimeout(15000);
InputStream in = socket.getInputStream();
StringBuilder time = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, "ASCII");
for (int c = reader.read(); c != -1; c = reader.read())
{ time.append((char) c);
}
System.out.println(time);
} catch (IOException ex) {
System.err.println(ex);
} finally {
if (socket != null) {
try
{ socket.close();
} catch
(IOException ex) {
// ignore
}}}}} 8
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
6.2.3 Writing to servers with Sockets
• Writing to sockets is quite similar to reading from them. Here you simply
ask the socket for an output stream as well as an input stream.
• Example:
• telnet dict.org 2628
• See the response and definition sent by the server, you never know how
the communication took place lets implement it in Java.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
• Open socket: Socket socket = new Socket("dict.org", 2628);
• Now the server sends response to the request. Use the input stream to read output.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 10
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
for (String line = reader.readLine();
!line.equals(".");
line = reader.readLine()) {
System.out.println(line);
}
• Finally, disconnect
from the server:
writer.write("quit\r\n");
writer.flush(); Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 11
6.3 Constructing and connecting Sockets: Basic
Constructors
• Each constructor for Socket specifies the host and the port to connect to.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
Example: Find active ports on a specified
host.
• This program helps determine the open ports and rouge servers using
these ports.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
6.3.2 Picking a Local Interface to Connect
From
• You can choose among the local interfaces by which you wish to establish a
socket connection to a server.
• The first two arguments in both constructors specify the host and port to connect
to.
• The last two arguments specify the local interface from which connection is
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 14
established.
6.3.3 Constructing without
•Connecting
All the constructors studied so far create the socket and open a network connection to a
remote host.
• But sometimes these tasks must be split. This can be done using constructor:
• public Socket()
• Later on, connection can be established by passing a SocketAddress to the connect() method.
• try {
Socket socket = new Socket();
// fill in socket options
SocketAddress address = new InetSocketAddress("time.nist.gov", 13);
socket.connect(address);
// work with the sockets...
} catch (IOException ex) {
15
System.err.println(ex);}Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
Original Constructor NoArgs Constructor
Socket socket = Socket socket = new Socket();
null; try { SocketAddress address = new
socket = new InetSocketAddress(SERVER, PORT);
Socket(SERVER, try {
PORT); socket.connect(address);
// work with the // work with the socket...
socket... } catch (IOException ex) {
} catch (IOException ex) { System.err.println(ex);
System.err.println(ex); } finally {
} finally { try
if (socket != null) { { socket.close
try ();
{ socket.close(); } catch
} catch (IOException
(IOException ex) { ex) {
// ignore //Programming,
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network ignore 4th edition, Elliotte Rusty Harold 16
6.3.4.1 Socket
Addresses
• The SocketAddress class represents a connection endpoint and has only
a constructor.
• The SocketAddress class acts as a convenient store for transient socket
connection information such as the IP address and port that can be reused to
create new sockets even after the original socket is disconnected and garbage
is collected.
• The Socket class has two methods that return SocketAddress objects.
• public SocketAddress getRemoteSocketAddress() : returns the address of the system being
connected
public SocketAddress getLocalSocketAddress(): returns the address from which the connection
is made 17
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
• Example: Connecting to Yahoo and store its address for reuse.
• Later on, we can use the closed socket info using the
address:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 18
6.3.4.2 Proxy Servers
• The proxy server that a socket uses is controlled by the socksProxyHost
and socksProxyPort system properties.
• These system properties are applicable for all the sockets in the system.
• However if you need to modify the proxy server for a single socket you
can employ the following constructor:
• public Socket(Proxy proxy)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
• SocketAddress proxyAddress = new InetSocketAddress("myproxy.example.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddress)
Socket s = new Socket(proxy);
SocketAddress remote = new InetSocketAddress("login.ibiblio.org", 25);
s.connect(remote);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 20
6.4 Getting information about a
socket
• Socket objects have several properties that are accessible through getter methods:
• Remote Address
• Remote Port
• Local Port
• There are no setter methods since the details are extracted from a socket object.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 21
• There are no setter methods since the details are extracted from a socket
object.
• Example get a socket’s information:
public class
staticSocketInfo
void main(String[]
{ args) { Command:
for (String host : args) { java SocketInfo.java
try { www.oreilly.com
Socket theSocket = new Socket(host, 80); www.oreilly.com
System.out.println("Connected to " + theSocket.getInetAddress() www.elharo.com
+ " on port " + theSocket.getPort() + " from port "
login.ibiblio.org
+ theSocket.getLocalPort() + " of "
+ theSocket.getLocalAddress());
} catch (UnknownHostException ex)
{ System.err.println("I can't find " +
host);
} catch (SocketException ex)
{ System.err.println("Could not connect to " +
host);
22
}}}}
} catch (IOException ex) Compiled
{ by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
Closed or Connected?
• The isClosed() method can be used to check either the socket is closed
or open?
• It returns boolean value; true if socket is open, false if socket is closed.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 23
• However it is still not perfect test.
• If the connection has never been made in the first place using the socket,
then isClosed() always returns false.
• Hence Socket class also has an isConnected() method, that tells weather a
socket has ever been connected to the remote host.
• So to check either the socket is open we need to use both the methods as
follows:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 24
toString()
• The Socket class overrides the standard toString() method to produce
a string that looks as follows:
• Socket[addr=www.oreilly.com/198.112.208.11,port=80,localport=50055]
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 25
6.5 Setting Socket Options
• Socket options specify how the actual sockets send and receive
data.
• Java has nine options for client side sockets:
• TCP_NODELAY
• SO_BINDADDR
• SO_TIMEOUT
• SO_LINGER
• SO_SNDBUF
• SO_RCVBUF
• SO_KEEPALIVE
• OOBINLINE
• IP_TOSCompiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 26
TCP_NODELA
Y
• Setting TCP_NODELAY to true ensures that packets are sent as quickly as
possible regardless of their size.
• Normally small packets are combined into larger packets before being sent.
• Nagle’s Algorithm: wait for acknowledgement before sending another packet.
• Inefficient for GUI programs such as games and remote access
• By default, the close() method closes the socket immediately but the system
still tries to send the remaining data.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 28
SO_TIMEOUT
• While reading data from socket, the read() method will listen until the no
data is available for reading.
• It does not disconnect the socket and can again be used for reading
purpose.
• For fast connections (10 Mbps and more) large buffers tend to improve performance.
• The SO_RCVBUF option controls the suggested buffer size for receiving data.
• The SO_SNDBUF option controls the suggested buffer size for sending data.
• public void setReceiveBufferSize(int size) throws SocketException, IllegalArgumentException
• Without this attribute a client can never know that the server is not
responding, and wait infinitely to get served.
• The receiver also processes this urgent data with high priority.
• By default, Java ignores urgent data received from a socket. However it can
be enabled using the following methods:
• However, ports need to be used interchangeably. Java by default does not allow
sharing of the port simultaneously.
• It allows another socket to bind to a port even if the data may be present for
previous socket.
• The class of service is stored in eight bit field called IP_TOS in the IP
header.
• A Network Client
Library
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 35
End of Unit
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 36
Unit 7 : Sockets for Clients
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
Introduction
• Previous Chapter: Socket for Clients
• Discussed sockets from clients viewpoint
• In other words, server sockets wait for connections while client sockets initiate connections.
• When a client on a remote host attempts to connect to that port, the server wakes up,
negotiates the connection between the client and the server, and returns a regular
Socket object representing the socket between the two hosts.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
7.1 Using ServerSockets
• The ServerSocket class contains everything needed to write servers in
Java.
• usual methods.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 3
• Basic life of a server program:
2. The ServerSocket listens for incoming connection on the port using its accept() method.
3. The accept() method returns a Socket object that connects the client and the server.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
Implementing a NIST time
Server
• Create a server socket that listens on port 13.
• Accept a connection
• Since the daytime server only speaks, we get OutputStream from socket and
the format is text we chain it to OutputStreamWriter.
• OutputStream out = connection.getOutputStream();
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
Writer writer = new OutputStreamWriter(writer, "ASCII")
• Now, we get the time and write it into the outputstream.
• Is it done? NO!!!
• The server cannot exit after a request is processed. It must listen for other
clients continuously.
• Solution: put all these steps inside a loop.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 6
• The final code becomes: (This is called an iterative server)
• ServerSocket server = new ServerSocket(port);
while (true) {
try (Socket connection = server.accept()) {
Writer out = new OutputStreamWriter(connection.getOutputStream());
Date now = new Date();
out.write(now.toString() +"\r\n");
out.flush();
} catch (IOException ex) {
// problem with one client; don't
shut down the server
System.err.println(ex.getMessage
}}
()); Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 edition, Elliotte Rusty Harold 7
th
7.2 Serving Binary
Data
• Sending binary data is quite simple. (we have done at very beginning ch. 2, 3)
• For serving binary data, we use an OutputStream that writes a byte array
rather than a writer that writes a string.
• i.e. We typecast the data as byte and write it to the OutputStream.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
Public class ServesBd{
Public final static int PORT = 37;
Public static void main (String[] args){
try(ServerSocket server = new ServerSocket(PORT)){
while (true){
try(Socket connection = server.accept()){
• It is quite simple:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 10
• public Void call() throws IOException {
try {
InputStream in = new BufferedInputStream(connection.getInputStream());
OutputStream out = connection.getOutputStream();
int c;
while ((c = in.read()) != -1) {
out.write(c);
out.flush();
}
} catch (IOException ex) {
System.err.println(ex);
} finally
{ connection.close
();
}
}return null; Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 11
Closing Server Socket
• After the server socket’s task is completed, it must be closed.
• Closing a server socket frees the port for other programs and the port can be used by the other
programs.
• A server side socket can be closed using the close() method on the ServerSocket object and
follows a try catch finally sequence:
• ServerSocket server = null;
try {
server = new
ServerSocket(port);
// ... work with the server
socket
} finally {
if (server != null) {
try
{ server.close();
// ignore} Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold
} catch 12
7.2 Logging:
• Logging is the process of recording error and warnings that occur within a system.
• Since a server runs for long periods of time, it might be important to debug
what happened to the server during the run.
• Hence it is necessary to record server logs and store for some period of time.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
What to Log?
• Two things are primarily stored in log messages:
• Requests
• Server Errors
• Servers maintain two different logfiles for these two different items.
• The audit log usually contains one entry for each connection made to the server.
• The error log contains mostly unexpected exceptions that occur while the server
is running.
• For instance, a server must log NullPointerException since it indicates error in
the server that must be fixed.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 14
• However the error log does not contain any client side errors such as
unexpected disconnection and illegal requests. They are saved in request log.
• Every entry in the error log must be investigated and resolved hence one should
ensure that everything should not be logged thinking that one might need it
someday
• As a developer only the important errors and exceptions must be logged. Error
logs that fill up with too many messages become ignored and useless.
• Also many systems provide several tools that can be used to analyze the recorded
logs. Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 15
How to Log?
• Many legacy programs still rely on third party logging libraries such as log4j or
Apache Commons Logging but Java has java.util.logging package available
that provides most needs.
• Use of the built in Java package eliminates the dependency of complex 3rd party
tools.
• Loggers provide several methods for recording log events, however you need to
assign log level to determine the severity of the log.
• The log() method of the Logger class can be used to log a error/warning.
• Example:
• Create a server socket that would be used by an HTTP server on port 80:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
Constructing without binding
• The noargs constructor of the ServerSocket can be used to create a
ServerSocket object that doesnot bind to a port.
• Such object cannot accept any connections and can be bound later using the
bind() methods.
• public void bind(SocketAddress endpoint) throws IOException
public void bind(SocketAddress endpoint, int queueLength) throws
IOException
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 20
• The general pattern is:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 21
7.4 Getting Information about Server
•Socket
All the ServerSockets occupy is the local address and the port.
• The ServerSocket class provides two getter methods that extract the local
address and port occupied by the server socket.
• Useful when you choose to use an arbitrary port by passing 0 as port value.
• SO_REUSEADDR
• SO_RCVBUF
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 24
SO_TIMEOUT
• SO_TIMEOUT defines the amount of time in milliseconds, that accept() waits for
an incoming connection.
• If the timeout value is set to 0, accept() will never timeout. (default = never time
out)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 26
SO_RCVBUF
• The SO_RCVBUF option sets the default receive buffer size for client
sockets accepted by the server socket.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 27
Class of Service
• Different services have different performance needs.
• For example live streaming video requires relatively high bandwidth while email can
be held for several hours without any harm.
• The ServerSocket specifies class of service using three parameters using numbers 1,
2 and 3 (higher number higher priority) that represent
• ConnectionTime, latency and bandwidth in order.
• A redirector
• A full-fledged
server.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 29
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 30
Unit 8 : Secure Sockets
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
Why Secure Sockets?
• Several internet backbone organizations allow government organizations to
access customers internet traffic.
• AT&T copies each packet to its mining server that can be accessed by National
Security Agency (NSA)
• Britian’s GCHQ taps into fiber-optic cables that carry most of the world’s
traffic
• Most of the encryption schemes are based on the key. A key can be thought as of
a general password that can be alphaneumeric and/or special symbols.
• In symmetric encryption the same key is used for encryption and decryption
i.e. E(k) = D(k)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 3
• In Asymmetric encryption, different keys are used for encryption and
decryption purpose. i.e. E(K1) ≠ D(K2).
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
8.2 Creating Secure Client
Sockets
• Using an encrypted SSL socket to an existing secure server is
simple.
• Create a SocketFactory object using SSLSocketFactory’s getDefault() method.
• SocketFactory factory = SSLSocketFactory.getDefault();
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
public abstract Socket createSocket(String host, int port) throws IOException, UnknownHostException
public abstract Socket createSocket(String host, int port, InetAddress interface, int localPort) throws
IOException, UnknownHostException
public abstract Socket createSocket(InetAddress host, int port, InetAddress interface, int localPort)
throws IOException, UnknownHostException
public abstract Socket createSocket(Socket proxy, String host, int port, boolean autoClose) throws
IOException
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 6
Example: Sending data to server from
client
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket socket = factory.createSocket("login.ibiblio.org", 7000);
Writer out = new OutputStreamWriter(socket.getOutputStream(), "US-ASCII");
out.write("Name: John Smith\r\n");
out.write("Product-ID: 67X-89\r\n");
out.write("Address: 1280 Deniston Blvd, NY NY 10003\r\n");
out.write("Card number: 4000-1234-5678-9017\r\n");
out.write("Expires: 08/05\r\n");
out.flush();
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 7
8.3 Event Handlers
• Network communications are slow compared to the speed of most computers.
• The necessary key generation and a connection setup can take several seconds.
• Java uses the event model to notify programs when the handshaking
between client and server is complete.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
• The interface declares the handshakeCompleted() method that receives
HandshakeCompletedEvent as an argument.
• The HandshakeCompletedEvent is a public class that provides four methods for getting
information about the event.
• Only the first socket will suffer the overhead time of key generation and
exchange.
• As a programmer, there is no any extra work that needs to be done. If you open
multiple secure sockets to one host on one port within short period of time. JSSE
will reuse the session key automatically.
• For example, if I wish to buy a book from Amazon and access the Amazon server, then the
server must prove that it is indeed the Amazon server and not other server.
• If mode = true, it indicates that the socket is in client mode and does not need
any authentication. (server acts as client and no authentication necessary)
• If mode = false, it indicates that the server needs to authenticate itself. (default)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
• The respective getter method can be used to determine either authentication
is necessary or not. (getUseClientMode();)
• If value = true, indicates that the clients invoking the server must
authenticate.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
8.6 Creating Secure Server
Socket
• The server side secure sockets are provided by the SSLServerSocketFactory
abstract class that extends ServerSocketFactory.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 14
8.7 Configure SSLServerSockets
• After creating a SSLServerSocket object, the next task is to adjust its behavior.
• The behavior defines how the socket operates. The following behavior can
be defined.
• Choosing the Cipher Suites
• Session Management
• Client Mode
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 15
Choosing the Cipher Suites
• The SSLServerSocket class has three methods to manipulate the cipher suites.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 16
Session Management
• Client and server both must agree to establish a session.
• The server uses the following methods to specify weather this will be allowed.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 17
Client Mode
• public abstract void setNeedClientAuth(boolean flag)
public abstract boolean getNeedClientAuth()
• Discussed earlier
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 18
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
Unit 9 : Non-Blocking I/O
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
Non-Blocking IO
•Introduction
Compared to CPUs, memory and even disks, networks are slow.
• When a command is executed the CPU has to wait for some time until the data
complete data is fetched or sent.
• We say that the I/O operation blocks other resources in that case.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
• Blocking I/O
• Blocking IO wait for the data to be write or read before returning. Java IO's
various streams are blocking. It means when the thread invoke a write() or
read(), then the thread is blocked until there is some data available for read, or
the data is fully written.
• Non blocking I/O
• Non blocking IO does not wait for the data to be read or write before
returning. Java NIO non- blocking mode allows the thread to request writing
data to a channel, but not wait for it to be fully written. The thread is
allowed to go on and do something else in a mean time.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 3
An Example Client
• Implementing a client that takes advantage of new I/O API, begin by invoking
the static factory method SocketChannel.open() that takes a SocketAddress
object indicating the host and the port to connect to.
• With a channel, you need to write to the channel itself. Rather than writing
byte arrays, we write ByteBuffer objects. [ByteBuffer objects have lines of
text each having 74 characters followed by a carriage return]
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
• Now we create a ByteBuffer that has 74-byte capacity using the static allocate() method.
• And pas this object to channel’s read() method. The channel fills the buffer with the data
it reads from the socket. int bytesRead = client.read(buffer);
• Extracting the byte array from the byte buffer requires flipping the buffer and
chaining buffer to a WritableByteChannel object
buffer.flip();
output.write(buffer);
buffer.clear();
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
An Example Server
• As in client invoke the ServerSocektChannel.open() method and chain it to
a ServerSocket using a the above obtained object before binding it to a port.
ServerSocket ss = serverChannel.socket();
ss.bind(new InetSocketAddress(19));
clientChannel.configureBlocking(false);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 6
9.2 Buffers
• In NIO all the I/O is buffered i.e. instead of reading and writing via inputstreams
and outputstreams, read and write are performed via buffers.
• A buffer is an fixed size list of primitive data type such as an integer, character,
long integer etc.
• Every buffer also has common methods to track key pieces of information:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 7
• Position: It denotes the next location in the buffer that will be read from or
written to. It starts at 0 and has a maximum value equal to the size of buffer. It
can be set or get with these two methods.
• public final int position()
public final Buffer position(int newPosition)
• Capacity: The maximum number of elements the buffer can hold. This is set
when the buffer is created and cannot be changed thereafter. It can be read using:
• public final int capacity()
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
• Limit: it denotes the end of accessible data in the buffer. Reading or writing past
this point without changing the limit.
• Mark: An index specified by client in the buffer. Ait can be set at current
position by invoking the mark() method. The current position is set to the
marked podition by invoking the reset() method.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
• The buffer superclass also provides other methods:
• public final Buffer clear(): clear method sets the sets the position to 0 and the limit to
the capacity. If any data is written, it replaces the existing data.
• public final Buffer rewind(): it sets the position to zero but dowsnot change the limit.
• public final Buffer flip(): sets the limit to the current position and the position to zero.
• public final int remaining(): the remaining method returns the number of elements in
the buffer between the current position and the limit.
public final boolean hasRemaining(): it returns true if the number of remaining
elements is greater than zero.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 10
Creating Buffers
• To deal with buffers one should know the subclass of the buffer and code
according to the buffer used.
• Allocate methods are generally used for input and wrap methods for
output purpose.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 11
Allocation:
• The basic allocate() method returns a new, empty buffer with fixed capacity. For
example the statements below create buffers of byte and int each of size 100.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
Direct Allocation: (Only in ByteBuffer)
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
Wrappin
•g Existing array of data can be put in buffer by using wrap() method and the
process is known as wrapping.
• Rather than allocating an new buffer and copying the data one by one, we
convert the data into array and use suitable buffer to wrap the data.
• For example:
• The read and write operations of a buffer are controlled by the position and
limits.
• Position points somewhere between zero and the max limit where the next
data will be read from or written into.
• Draining is the process of getting the data stored in the buffer. If you directly use the get()
method from the buffer you would get the null character or the last character. (Position
points to empty space or last location)
• Hence we flip the buffer using buffer.flip(), it sets limit to the position and position to 0
and now drain it into a new string.
• Example:
buffer.put(4, C'oom'p)iled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 th edition, Elliotte Rusty Harold
17
Bulk Methods
• Rather than filling and draining one element at a time, buffers allow to work with
blocks of data.
• Working with blocks of data makes it faster and easier to manipulate data.
• Different buffer classes have bulk methods that fill and drain an array of their type
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
Data Conversion
• All data in Java can be resolved into bytes. i.e. any primitive data supported by
Java such as int, double, float, char etc. can be written as byts.
• The ByteBuffer class provides abstract methods to put and get data to and from a
buffer.
• View buffers can be created with one of these six methods in ByteBuffer
objects.
try {
SocketAddress address = new InetSocketAddress(args[0], port);
SocketChannel client = SocketChannel.open(address);
ByteBuffer buffer = ByteBuffer.allocate(4);
IntBuffer view = buffer.asIntBuffer();
..
.. Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 22
Compacting Buffers
• Compacting buffers is the process of shifting any remaining data in the buffer to
the start of the buffer.
• Compacting sets the new buffer position point to the end of data hence new data
can be written.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 23
Duplicating Buffers
• Buffers can be duplicated to deliver the same information over multiple
channels. The following classes have duplicate method that allow to duplicate
buffers.
public abstract ByteBuffer duplicate()
public abstract IntBuffer duplicate()
public abstract ShortBuffer duplicate()
public abstract FloatBuffer duplicate()
public abstract CharBuffer duplicate()
public abstract DoubleBuffer duplicate()
• The duplicated buffers share the same data and changes in one buffer are reflected
in another. Hence these methods are recommended to use while only reading
from the buffers.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 24
Slicing Buffers
• Slicing is a variant of duplicating.
• Slicing also creates a new buffer that shares the data with original buffer, however
the slice’s zero position is the current position of the original buffer and the
slice’s capacity goes upto the source buffer limit.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 26
Object Methods
• All the buffer classes provide the common equals(), hashCode() and toString() methods.
• The toString method is used for debugging purpose and displays the position,
limit and capacity(empty) of the buffer
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 28
9.3 Channels
• Channels move blocks of data into and out of buffers to and from various I/O
sources such as sockets and files.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 29
9.3.1 SocketChannel
• The SocketChannel class reads from and writes to TCP sockets and the data must
be encoded in ByteBuffer objects for reading and writing..
• Connecting:
• The SocketChannel class doesnot have any public constructors. Instead, you
create a new SocketChannel using one of the two static methods.
• public static SocketChannel open(SocketAddress remote) throws IOException
public static SocketChannel open() throws IOException
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 30
• The first method makes the connection as follows:
• The noargs version doesnot immediately connect and must be connected later
using connect() method, it helps configure non-blocking I/O.
channel.configureBlocking(false)
; channel.connect(address);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 31
• Reading, Writing and Closing
• To read data from a SocketChannel, first create a ByteBuffer the channel can store
data and pass it to the read method.
• Channels must be closed once task is completed . Use the close() method to
close the socket.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 32
9.3.2 ServerSocketChannel
• The ServerSocketChannel as one purpose to accept incoming connections,
as
SocketChannel it also uses open() method to create a new object.
• try {
ServerSocketChannel server = ServerSocketChannel.open();
SocketAddress address = new InetSocketAddress(80);
server.bind(address);
• The ServerSocketChannel object has the accept() method to listen for incoming
connections.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 33
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 34
Unit 10 : UDP
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
10.1 UDP
•Protocol
Data transmission over transport layer is based on use of two common
protocols: TCP and UDP.
• The TCP is a reliable protocol, in the sense that TCP ensures that the data
sent from one node must be received at another node at any cost.
• But this reliability comes at the cost of speed, hence is not suitable for
short
transmissions.
• The UDP is an alternative to TCP that is very quick, but not reliable. Data
sent over Compiled
UDPbymay or may not arrive at the destination
Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 edition, Elliotte Rusty Harold
th 2
• UDP is primarily used where speed matters than reliability.
• For example consider the real time audio and video, here speed matters as the lost
pixels remain static as in the previous frame.
• Since TCP and UDP have their own applications we will deal with UDP in this chapter.
• The DatagramPacket class stuffs bytes of data into UDP packets called datagrams and
unstuff datagrams at the receiving side.
• To send data over UDP, data must be put in a DatagramPacket and send the packet using a
DatagramSocket. DatagramPacket is received form the DatagramSocket and fetch
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 edition, Elliotte Rusty Harold
th 3
• In UDP the destination address is included in the packet itself hence socket
only needs to know the port on which to listen for connections or port used to
send data.
• UDP can utilize a single DatagramSocket to send and receive data from many
hosts and a socket is not dedicated for a single connection as in TCP.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 4
UDP
Clients
• We will implement NIST daytime server but this time using the UDP protocol.
• Step 2: timeouts are important for UDP than TCP since UDP is not reliable. So
set SOTIMEOUT socket option.
socket.setSoTimeout(10000);
• Now we need to set the packets, 1 packet to send request and another packet to
receive data.
InetAddress host = InetAddress.getByName("time.nist.gov");
DatagramPacket request = new DatagramPacket(new byte[1], 1, host, 13);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
(byte[] = data to send, length of datagram, host to connect, remote port no)
byte[] data = new byte[1024];
DatagramPacket response = new DatagramPacket(data, data.length);
• Now we can send the 1st packet over the socket and receive response too.
socket.send(request);
socket.receive(response);
• The constructor, send() and receive methods throw an IOException hence iit is good
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 6
practice to wrap inside try catch block.
UDP
•Servers
A UDP server follows similar pattern as a UDP client. The key differences
are:
• It receives before sending
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 7
try (DatagramSocket socket = new DatagramSocket(13)) {
while (true) {
try {
DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
socket.receive(request);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
10.4 DatagramPacket Class
• Describe UDP header
• IP header+ UDP
Header+ Data
= Datagram
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
• A UDP datagram is represented by an instance of the DatagramPacket
class.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 10
10.4.1 Constructors
• Different constructors depending on weather to send or receive the data.
• However, all these constructors take a byte array to hold datagram’s data and the
number of bytes in that array as the length.
public DatagramPacket(byte[] buffer, int length): if this constructor is used, when a socket
receives a datagram, it stores the datagram’s data beginning at buffer[0] till the length
bytes have been written into the buffer.
public DatagramPacket(byte[] buffer, int offset, int length): when it is used, storage begins
at buffer[offset]
• For both cases, length must be less than or equal to buffer length.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 11
• Example:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
• Following constructors are used for sending datagrams:
• Each constructor has the data to send of length bytes as the byte array starting
at offset or 0 if offset is not specified.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
• Following code creates a new DatagramPacket filled with data “This is a test”
in UTF-8 destined for port 7 of the www.ibiblio.org.
String s = "This is a test";
byte[] data = s.getBytes("UTF-8");
try {
InetAddress ia = InetAddress.getByName("www.ibiblio.org");
int port = 7;
DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);
// send the packet...
} catch (IOException ex)
}
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 14
10.4.2 The get
Methods
• DatagramPacket has six get methods to extract different parts of a datagram including the data
itself and several parts of header.
• public InetAddress getAddress(): returns the InetAddress obj containing the address of the
remote host.
• public int getPort(): returns an integer that specifies the remote port.
• public byte[] getData(): returns a byte array containing the data from the datagram.
• public int getLength(): returns the number of bytes of data in the datagram
• public void setData(byte[] data): it changes the payload of the UDP datagram. It is useful
when data is large and is divided into multiple datagrams. Object can be utilized to send
multiple data over the same object.
• public void setData(byte[] data, int offset, int length): overloaded setData()
method that permits changes to existing datagram object. Useful
when the size of existing datagram needs to be modified.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 16
• public void setAddress(InetAddress remote): changes the destined address of a datagram
packet. Useful to utilize a single object to send data to multiple recipients.
• public void setAddress(SocketAddress remote): changes both the address and port of
the destination.
• public void setLength(int length): changes the number of bytes of data in the internal
buffer. It is often used to discard the unused space.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 17
10.5 DatagramSocket class
• To send or receive a DatagramPacket, you must open a datagram socket. In Java,
a datagram socket is created and accessed through the DatagramSocket class.
public class DatagramSocket extends Object
• All datagram sockets bind to a local port, on which they listen for incoming data.
• For a client, the local port is not of interest, any unused random port can
be used.
• For a server, clients need to know the port on which the server is listening
hence the local port must be modified.
try {
DatagramSocket client = new DatagramSocket();
// send packets...
} catch (SocketException ex) {
System.err.println(ex);
}
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 19
• public DatagramSocket(int port) throws SocketException: creates a socket that listens for
incoming datagrams on a particular port. We use this constructor to write server side
program that listens for incoming connections on a port.
• Two programs can use the same port if one program uses UDP and another uses TCP
• After the send and receive tasks are completed the port
occupied by the socket
must be freed. For that we use the close() method.
• But it is not what we want, for example; an applet must be allowed only to talk
to the applet host.
• The methods to be discussed later will help you manage from whom to
receive and send datagrams while rejecting others.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 22
• public void connect(InetAddress host, int port): it specifies that the DatagramSocket will only
send packets to and receive packets from the specified remote host on the specified remote
port.
• Any attempt to send packets to other host throws IllegalArgumentException while packets
from other hosts will be discarded.
• public void disconnect(): it breaks the connection established by the connect() method. i.e. the
socket can send and receive packets from any host when disconnect() method is called.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 23
10.6 Socket Options
• Java supports six socket options for UDP:
• SO_TIMEOUT: specifies the amount of time in milliseconds that receive() waits for an
incoming datagram before throwing InterruptedException. Has following methods:
Both methods set the suggested buffer size for receiving and sending purpose
respectively.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 24
• • SO_REUSEADDR: Defines whether multiple sockets can bind to the same port
and address at the same time. Methods are similar to TCP.
• SO_BROADCAST: controls either the socket is allowed to send and receive
packets from broadcast addresses . Following methods control it:
public void setBroadcast(boolean on) throws SocketException
public boolean getBroadcast() throws SocketException
•IP_TOS: similar to TCP, defines a traffic class between 0 to 255, that prioritize the
datagrams.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 25
10.7 UDP
•Applications
UDP client
• UDP Server
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 26
10.8 DatagramChannel: Using datagram
channel
• The DatagramChannel class is used for non-blocking UDP applications(Remember
SocketChannel and ServerSocketChannel were used for Nonblocking TCP
applications)
• This channel is not bound to any port, hence it must be bind using the socket()
method over the channel that returns the DatagramSocket object. Finally use bind()
that takes SocketAddress object. For example:
SocketAddress address = new InetSocketAddress(3141);
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 27
• As the DatagramSocket class it also has send() and receive() method to send and
receive data over NIO.
• And finally the write() method that acts an alternative to send and is used after the
connect() method is called.
• The close()Compiled
method at the end is used to free the occupied port after task is complete.
by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4 edition, Elliotte Rusty Harold
th 28
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 29
Unit 11 : IP
Multicast
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 1
Multicasting
• Multicasting refers to the process of sending data from one host to many different
hosts but not to everyone in the network.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 2
Multicast Addresses and
•Groups
The hosts that participate in the multicast communication are collectively
referred
as Multicast groups. A multicast group shares a multicast address.
• Each multicast group has a multicast address that identifies the group. All the
hosts within the group share the same multicast address. Hence multicast
address is the shared address of the multicast group.
• One problem in UDP multicasting is the TTL value. TTL defines the maximum
intermediate hops an packet is allowed to pass. However in UDP, the TTL limits
the multicast geographically.
• For example, a TTL value of 16 limits the packet to local area while the TTL
of 127 sends the packet around the world.
• When the sender forwards multicast datagram to local network, the hosts in local
multicast group receive the datagram and the the datagram’s TTL is checked, if
the TTL is greater than 1 it is routed to other networks that have members of the
multicast group. The routing is handled by the routers.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 5
Routers and Routing
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 6
• Routing for multicast datagrams can be achieved using one of the possible two
configurations; use of the multicast socket and without using multicast
sockets.
• Configuration on the left side of the previous figure utilizes the multicast
sockets. In this
configuration a single socket is used to send data from server’s router to the client’s router.
The client router then duplicates the stream and sends it to each of the clients.
• Without multicast sockets (figure in right) the server needs to use separate but
identical streams to send the data to the client’s router.
• Create a MulticastSocket using the constructor, make sure to specify the port to
listen for connections and data.
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 8
• Now join a multicast group using the MulticastSocket’s joinGroup() method.
• Now receive the data as done in UDP; use a byte array and
a DatagramPacket
ms.leaveGroup(group)
; ms.close();
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 9
11.2.1 Constructors
• There are three constructors that allow you to listen over a random port, or over
the specified port and over a specific network interface and port combined
together.
• Example:
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 11
11.2.2 Communcating with a Multicast Group
• Once a MulticatSocket has been created, it can perform four key operations:
• To join a group, pass an InetAddress or SocketAddress for the multicast group to the
joinGroup() method.
public void joinGroup(InetAddress address) throws IOException
public void joinGroup(SocketAddress address, NetworkInterface interface) throws IOException
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 12
• Receiving datagrams is similar as receiving the unicast datagrams.
• After that, use the leaveGroup() method to stop receiving datagrams from
specified multicast group.
public void leaveGroup(InetAddress address) throws IOException
public void leaveGroup(SocketAddress multicastAddress, NetworkInterface interface)
throws
IOException
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 13
Compiled by Manoj Pokharel@ Nepathya College, Ref. Java Network Programming, 4th edition, Elliotte Rusty Harold 14