Unit IV Multithreadingappletsnetworking
Unit IV Multithreadingappletsnetworking
UNIT IV
UNIT IV
Multithreading: Fundamentals, Thread class, Runnable interface, Creating multiple
threads, Life cycle of thread, Thread priorities, Synchronization, Thread communication,
Suspending, Resuming and Stopping threads.
Applets: Basics, skeleton, Initialization and termination, Repainting, Status window,
Passing parameters.
Networking: Basics, Networking classes and interfaces, InetAddress, Inet4Address and
Inet6Address, TCP/IP Client Sockets, URL, URLConnection, HttpURLConnection, The URI
class, Cookies, TCP/IP Server sockets, Datagrams.
MULTITHREADING: FUNDAMENTALS
JAVA PROGRAMMING
UNIT-IV 2 KNREDDY
CREATING A THREAD
We create a thread by instantiating an object of type Thread. Java defines two ways in which
this can be accomplished:
• Can implement the Runnable interface.
• can extend the Thread class, itself.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. We can construct a thread on any
object that implements Runnable.
To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
Inside run( ), we will define the code that constitutes the new thread. The thread will end
when run( ) returns.
After creating a class that implements Runnable, instantiate an object of type Thread from
within that class. Thread defines several constructors.
Thread(Runnable threadOb)
In this constructor, threadOb is an instance of a class that implements the Runnable
interface. This defines where execution of the thread will begin.
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )
Here is an example that creates a new thread and starts it running:
// Create a thread by implementing Runnable.
class MyThread implements Runnable {
String thrdName;
MyThread(String name) {
thrdName = name;
}
// Entry point of thread.
public void run() {
System.out.println(thrdName + " starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrdName +", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
}
class UseThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
JAVA PROGRAMMING
UNIT-IV 3 KNREDDY
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
System.out.println("Main thread ending.");
}
}
Simple Improvements:
It is possible to have a thread begin execution as soon as it is created.
It is possible to give the name of thread when it is created.
For this use the following version of Thread constructor.
Thread(Runnable threadOb, String name)
Name of the thread can be obtained by calling getName() defined by Thread.
final String getName()
Name of the thread can be set by using setName()
final void setName( String threadName)
// Improved MyThread.
class MyThread implements Runnable {
Thread thrd;
// Construct a new thread.
MyThread(String name) {
thrd = new Thread(this, name);
thrd.start(); // start the thread
}
// Begin execution of new thread.
public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrd.getName() +", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}
class UseThreadsImproved {
public static void main(String[] args) {
System.out.println("Main thread starting.");
MyThread mt = new MyThread("Child #1");
for(int i=0; i < 50; i++) {
System.out.print(".");
try {
Thread.sleep(100);
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
System.out.println("Main thread ending.");
}
}
JAVA PROGRAMMING
UNIT-IV 4 KNREDDY
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrd.getName() +", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}
class MoreThreads {
try {
Thread.sleep(100);
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
JAVA PROGRAMMING
UNIT-IV 5 KNREDDY
// Use isAlive().
class MoreThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
do {
System.out.print(".");
try {
Thread.sleep(100);
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
} while (mt1.thrd.isAlive() ||mt2.thrd.isAlive() ||mt3.thrd.isAlive());
// Use join().
class JoinThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
try {
mt1.thrd.join();
System.out.println("Child #1 joined.");
mt2.thrd.join();
System.out.println("Child #2 joined.");
mt3.thrd.join();
System.out.println("Child #3 joined.");
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted. ");
}
System.out.println("Main thread ending.");
}
}
JAVA PROGRAMMING
UNIT-IV 6 KNREDDY
THREAD PRIORITIES:
Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
Thread priorities are integers that specify the relative priority of one thread to another.
A higher priority thread doesn’t run any faster than a lower-priority thread if it is the only
thread running. Instead, a thread’s priority is used to decide when to switch from one running
thread to the next. This is called a context switch.
The rules that determine when a context switch takes place are simple:
• A thread can voluntarily relinquish control.
• A thread can be preempted by a higher-priority thread.
We can change a thread’s priority by calling setPriority(), which is a member of a Thread.
final void setPriority(int level)
Here level specifies the new priority setting for the calling thread.
3 constants defiend in Thread class:
o public static int MIN_PRIORITY
o public static int NORM_PRIORITY
o public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.
We can obtain the current priority setting by calling the getPriority() method of Thread.
final int getPriority()
SYNCHRONIZATION:
When using multiple threads, it is sometimes necessary to coordinate the activities of two or
more. The process by which this is achieved is called synchronization.
Key to synchronization in Java is the concept of the monitor, which controls the access to an
object. A monitor works by implementing the concept of a lock.
When an object is locked by one thread, access to the object by another thread is restricted.
Synchronization is supported by the keyword synchronized.
JAVA PROGRAMMING
UNIT-IV 7 KNREDDY
answer = sa.sumArray(a);
System.out.println("Sum for " + thrd.getName() +" is " + answer);
try {
mt1.thrd.join();
mt2.thrd.join();
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
}
O/P:
Child #1 starting.
Child #2 starting.
Running total for Child #1 is 1
Running total for Child #1 is 3
Running total for Child #1 is 6
Running total for Child #1 is 10
Running total for Child #1 is 15
Running total for Child #2 is 1
Sum for Child #1 is 15
Child #1 terminating.
Running total for Child #2 is 3
Running total for Child #2 is 6
Running total for Child #2 is 10
Running total for Child #2 is 15
Sum for Child #2 is 15
Child #2 terminating.
Child #1 starting.
Child #2 starting.
Running total for Child #2 is 1
Running total for Child #1 is 1
JAVA PROGRAMMING
UNIT-IV 8 KNREDDY
JAVA PROGRAMMING
UNIT-IV 9 KNREDDY
class Sync {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
try {
mt1.thrd.join();
mt2.thrd.join();
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
}
JAVA PROGRAMMING
UNIT-IV 10 KNREDDY
JAVA PROGRAMMING
UNIT-IV 11 KNREDDY
O/P:
Put: 0
Press Control-C to stop.
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
Put: 7
Got: 7
Put: 8
Got: 8
Put: 9
Got: 9
Put: 10
Got: 10
JAVA PROGRAMMING
UNIT-IV 12 KNREDDY
JAVA PROGRAMMING
UNIT-IV 13 KNREDDY
}
// Stop the thread.
synchronized void myStop() {
stopped = true;
ob1.mySuspend();
System.out.println("Suspending thread.");
Thread.sleep(1000);
ob1.myResume();
System.out.println("Resuming thread.");
Thread.sleep(1000);
ob1.mySuspend();
System.out.println("Suspending thread.");
Thread.sleep(1000);
ob1.myResume();
System.out.println("Resuming thread.");
Thread.sleep(1000);
ob1.mySuspend();
System.out.println("Stopping thread.");
ob1.myStop();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
// wait for thread to finish
try {
ob1.thrd.join();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
JAVA PROGRAMMING
UNIT-IV 14 KNREDDY
OUTPUT:
My Thread starting.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
Suspending thread.
Resuming thread.
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
Suspending thread.
81 Resuming thread.
82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110
111 112 113 114 115 116 117 118 119 120
Stopping thread.
My Thread exiting.
Main thread exiting.
JAVA PROGRAMMING
UNIT-IV 15 KNREDDY
APPLETS
Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and run as part of a web document.
There are two general varieties of applets: those based solely on the Abstract Window Toolkit
(AWT) and those based on Swings. Both AWT and Swing support creation of Graphical User
Interface (GUI).
Let examine a simple applet:
// A minimal AWT-based applet.
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Java makes applets easy.", 20, 20);
}
}
This applet begins with two import statements.
The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT, not through the console-based I/O classes. The
AWT contains support for a window-based, graphical user interface.
The second import statement imports the applet package, which contains the class Applet.
Every applet that you create must be a subclass (either directly or indirectly) of Applet.
The next line in the program declares the class SimpleApplet. This class must be declared as
public, because it will be accessed by code that is outside the program.
Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be
overridden by the applet. paint( ) is called each time that the applet must redisplay its
output.
The paint( ) method has one parameter of type Graphics. This parameter contains the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This
method outputs a string beginning at the specified X,Y location. It has the following general
form: void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y. In a Java window, the upperleft
corner is location 0, 0.
The applet does not have a main( ) method.
An applet begins execution when the name of its class is passed to an applet viewer or to a
network browser.
There are two ways in which you can run an applet:
• Executing the applet within a Java-compatible web browser.
• Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes
your applet in a window. This is generally the fastest and easiest way to test your applet.
To execute SimpleApplet with an applet viewer:
1. Edit a Java source file.
2. Compile your program.
3. Execute the applet viewer, specifying the name of your applet’s source file.
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer SimpleApplet.java. Now
Html file is not required but it is for testing purpose only.
The SimpleApplet source file look like this:
import java.awt.*;
import java.applet.*;
/*
<applet code=”SimpleApplet” width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Java makes applets easy.", 20, 20);
}
}
JAVA PROGRAMMING
UNIT-IV 16 KNREDDY
// Called second, after init(). Also called whenever the applet is restarted.
public void start() {
// start or resume execution
}
JAVA PROGRAMMING
UNIT-IV 17 KNREDDY
REQUESTING REPAINT:
An AWT- based applet writes to its window only when its paint() method is called by the run-
time system.
Whenever an applet needs to update the information displayed in its window, it simply calls
repaint()
The repaint() method is defined by the AWT’s Component class and inherited by Applet. It
causes the run-time system to execute a call to the applet’s paint() method.
The simplest version of repaint() is :
void repaint()
JAVA PROGRAMMING
UNIT-IV 18 KNREDDY
JAVA PROGRAMMING
UNIT-IV 19 KNREDDY
The volatile modifier tells the compiler that the variable modified by volatile can be changed
unexpectedly by other parts of your program.
When an instance variable is declared as transient, then its value need not persist when an
object is stored.
Sometimes, knowing the type of an object during run time is useful. Java provides the run-
time operator instanceof:
The instanceof operator has this general form:
objref instanceof type
Here, objref is a reference to an instance of a class, and type is a class type. If objref is of the
specified type or can be cast into the specified type, then the instanceof operator evaluates to
true. Otherwise, its result is false.
By modifying a class, a method, or interface with strictfp, you ensure that floating-point
calculations (and thus all truncations) take place precisely as they did in earlier versions of
Java. When a class is modified by strictfp, all the methods in the class are also modified by
strictfp automatically.
Java provides the native keyword, which is used to declare native code methods. Once
declared, these methods can be called from inside your Java program just as you call any
other Java method.
assert is used during program development to create an assertion, which is a condition that
should be true during the execution of the program.
The assert keyword has two forms. The first is shown here:
assert condition;
Here, condition is an expression that must evaluate to a Boolean result. If the result is true,
then the assertion is true and no other action takes place. If the condition is false, then the
assertion fails and a default AssertionError object is thrown.
The second form of assert is shown here:
assert condition: expr;
In this version, expr is a value that is passed to the AssertionError constructor. This value is
converted to its string format and displayed if an assertion fails.
JAVA PROGRAMMING
UNIT-IV 20 KNREDDY
NETWORKING BASICS
The core of Java’s networking support is the concept of a socket. A socket identifies an
endpoint in a network.
Sockets are at the foundation of modern networking because a socket allows a single
computer to serve many different clients at once, as well as to serve many different types of
information. This is accomplished through the use of a port, which is a numbered socket on a
particular machine.
A server process is said to “listen” to a port until a client connects to it. A server is allowed to
accept multiple clients connected to the same port number, although each session is unique.
Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level routing
protocol that breaks data into small packets and sends them to an address across a network,
which does not guarantee to deliver said packets to the destination.
Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string
together these packets, sorting and retransmitting them as necessary to reliably transmit
data.
A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to
support fast, connectionless, unreliable transport of packets.
A key component of the Internet is the address. Every computer on the Internet has one. An
Internet address is a number that uniquely identifies each computer on the Net. Originally, all
Internet addresses consisted of 32-bit values, organized as four 8-bit values. This address
type was specified by IPv4 (Internet Protocol, version 4).
IPv6 uses a 128-bit value to represent an address, organized into eight 16-bit chunks.
The name of an Internet address, called its domain name, describes a machine’s location in a
name space.
For example, www.SREC.com is in the COM top-level domain; it is called SREC, and www
identifies the server for web requests.
An Internet domain name is mapped to an IP address by the Domain Naming Service (DNS).
This enables users to work with domain names, but the Internet operates on IP addresses.
JAVA PROGRAMMING
UNIT-IV 21 KNREDDY
InetAddress class
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address. The InetAddress class hides the number inside. InetAddress can
handle both IPv4 and IPv6 addresses.
The InetAddress class has no visible constructors. To create an InetAddress object, use one
of its static methods.
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local
host. The getByName( ) method returns an InetAddress for a host name passed to it. If these
methods are unable to resolve the host name, they throw an UnknownHostException.
There are several methods that can be called on an instance of InetAddress.
String getHostAddress()
String getHostName()
The getHostAddress() method returns a string that lists the host IP address using its
numeric form. The getHostName() address returns the name that represents the host
address.
// Demonstrate InetAddress.
import java.net.*;
class InetAddressDemo {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.mcgraw-hill.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
System.out.println();
address = InetAddress.getByName("www.knreddycse.weebly.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
System.out.println();
address = InetAddress.getByName("www.srec.com");
System.out.println("Host name: " + address.getHostName());
System.out.println("Address: " + address.getHostAddress());
}
catch (UnknownHostException exc) {
System.out.println(exc);
}
}
}
OUTPUT:
Host name: www.mcgraw-hill.com
Address: 184.26.168.92
JAVA PROGRAMMING
UNIT-IV 22 KNREDDY
We can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods
InputStream getInputStream() Returns the input stream associated with the
throws IOException invoking socket.
OutputStream getOutputStream() Returns the output stream associated with
throws IOException the invoking socket.
Several other methods are available, including connect( ), which allows you to specify a new
connection; isConnected( ), which returns true if the socket is connected to a server;
isBound( ), which returns true if the socket is bound to an address; and isClosed( ), which
returns true if the socket is closed. To close a socket, call close( ).
Closing a socket also closes the I/O streams associated with the socket. Beginning with
JDK 7, Socket also implements AutoCloseable, which means that you can use a try
with-resources block to manage a socket.
// Demonstrate Sockets.
import java.net.*;
import java.io.*;
class SocketDemo {
public static void main(String[] args) {
int ch;
Socket socket = null;
try {
// Create a socket connected to whois.internic.net, port 43.
socket = new Socket("whois.internic.net", 43);
JAVA PROGRAMMING
UNIT-IV 23 KNREDDY
// Send request.
out.write(buf);
// Send request.
out.write(buf);
JAVA PROGRAMMING
UNIT-IV 24 KNREDDY
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.knreddycse.weebly.com:80/index.html");
OUTPUT:
Protocol: http
Port: 80
Host: www.knreddycse.weebly.com
File: /index.html
JAVA PROGRAMMING
UNIT-IV 25 KNREDDY
URLConnection class
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
These attributes are exposed by the HTTP protocol specification and, as such, only make
sense for URL objects that are using the HTTP protocol.
URLConnection defines several methods. Here is a sampling:
Method Description
int getContentLength() Returns the size in bytes of the content
associated with the resource. If the length is
unavailable,-1 is returned.
long getContentLengthLong() Returns the size in bytes of the content
associated with the resource. If the length is
unavailable,-1 is returned.(added by JDK7)
String getContentType() Returns the type of content found in the
resource. Returns null if the content type is not
available.
long getDate() Returns the time and date of the response
represented in terms of mill seconds since
January 1, 1970 GMT. Zero is returned if the
time and date are not available.
long getExpiration() Returns the expiration time and date of the
response represented in terms of mill seconds
since January 1, 1970 GMT. Zero is returned if
the expiration date is not available.
String getHeaderField(int idx) Returns the value of the header field at the idx.
Returns null if the value if idx exceeds the
number of fields.
String getHeaderField(String filedName) Returns the value of the header field whose name
is specified by fieldName. Returns null if the
specified name is not found
String getHeaderFieldKey(int idx) Returns the header field key at index idx.
Returns null if the value of idx exceeds the
number of fields
Map<String,List<String>> Returns a map that contains all of the header
getHeaderFields() fields and values
long getLastModified() Returns the time and date, represented in terms
of milli seconds since January 1, 1970 GMT, of
the last modification of the resource. Zero if
returned if the last modified date is unavailable.
InputStream getInputStream() Returns an InputStream that is linked to the
throws IOException connection.
OutputStream getOutputStream() Returns an OutputStream that is linked to the
throws IOException connection.
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class UCDemo
{
public static void main(String[] args) {
InputStream in = null;
URLConnection connection = null;
try {
URL url = new URL("http://www.mcgraw-hill.com");
connection = url.openConnection();
// get date
long d = connection.getDate();
if(d==0)
System.out.println("No date information.");
JAVA PROGRAMMING
UNIT-IV 26 KNREDDY
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " + connection.getContentType());
// get expiration date
d = connection.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
// get last-modified date
d = connection.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
long len = connection.getContentLengthLong();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
in = connection.getInputStream();
int ch;
while (((ch = in.read()) != -1)) {
System.out.print((char) ch);
}
} else {
System.out.println("No content available.");
}
} catch(IOException exc) {
System.out.println("Connection Error: " + exc);
} finally {
try {
if(in != null) in.close();
} catch(IOException exc) {
System.out.println("Error closing connection: " + exc);
}
}
}
}
HttpURLConnection
Java provides a subclass of URLConnection that provides support for HTTP connections.
This class is called HttpURLConnection.
HttpURLConnection in obtained, by calling openConnection( ) on a URL object, but it must
cast the result to HttpURLConnection.
Once a reference to an HttpURLConnection object is obtained, we can use any of the
methods inherited from URLConnection.
There are several methods defined by HttpURLConnection.
JAVA PROGRAMMING
UNIT-IV 27 KNREDDY
// Demonstrate HttpURLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLConnectionDemo
{
public static void main(String[] args) {
try {
URL url = new URL("http://www.mcgraw-hill.com");
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
JAVA PROGRAMMING
UNIT-IV 28 KNREDDY
Cookies
The java.net package includes classes and interfaces that help manage cookies and can be
used to create a stateful (as opposed to stateless) HTTP session.
The classes are CookieHandler, CookieManager, and HttpCookie.
The interfaces are CookiePolicy and CookieStore.
DATAGRAMS
Datagrams provide an alternative to the TCP/IP style networking.
Datagrams are bundles of information passed between machines. Once the datagram has
been released to its intended target, there is no assurance that it will arrive or even that
someone will be there to catch it. Likewise, when the datagram is received, there is no
assurance that it hasn’t been damaged in transit or that whoever sent it is still there to
receive a response.
Java implements datagrams on top of the UDP protocol by using two classes: the
DatagramPacket object is the data container, while the DatagramSocket is the mechanism
used to send or receive the DatagramPackets.
DatagramSocket
DatagramSocket defines four public constructors. They are:
DatagramSocket( ) throws SocketException
DatagramSocket(int port) throws SocketException
DatagramSocket(int port, InetAddress ipAddress) throws SocketException
DatagramSocket(SocketAddress address) throws SocketException
DatagramSocket defines many methods. Two of the most important are send() and receive():
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends a packet to the port specified by packet. The receive( ) method
waits for a packet to be received from the port specified by packet and returns the result.
DatagramSocket also defines the close( ) method, which closes the socket. Beginning with
JDK 7, DatagramSocket implements AutoCloseable, which means that a DatagramSocket
can be managed by a try-with-resources block.
JAVA PROGRAMMING
UNIT-IV 29 KNREDDY
DatagramPacket
DatagramPacket defines several constructors. They are:
DatagramPacket(byte data [ ], int size)
DatagramPacket(byte data [ ], int offset, int size)
DatagramPacket(byte data [ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data [ ], int offset, int size, InetAddress ipAddress, int port)
DatagramPacket defines several methods that give access to the address and port number of
a packet, as well as the raw data and its length.
In general, the get methods are used on packets that are received and the set methods are
used on packets that will be sent.
InetAddress getAddress() Returns the address of the source(for datagrams being received)
or destination ( for datagrams being sent)
byte[] getData() Returns the byte array that contains the data buffer. Mostly used
to retrieve data from the datagram after it has been received
int getLength() Returns the number of bytes of data contained in the buffer. This
may be less than the size of the underlying byte array
int getOffset() Returns the starting index of the data in the buffer
int getPort() Returns the port number used by the host on the other side of the
connection
void setData(byte[] data) Sets the packets data to data, the offset to zero, and the length to
the number of bytes in data.
void setData(byte[] data, int Sets the packets data to data, the offset to idx, and the length to
idx, int size) size.
void setLength(int size) Sets the packets data to size. This value plus the offset must not
exceed the length of the underlying bytes array
A Datagram Example:
The following example demonstrates datagrams by implementing a very simple client and
server. In this example the server reads string entered at the keyboard and sends them to the
client. The client simply waits until it receives a packet and then displays the string. This
process continues until ‘stop’ is entered. In that case, both the client and server terminate.
// Demonstrate datagrams -- server side.
import java.net.*;
import java.io.*;
class DGServer {
// These ports were chosen arbitrarily. You must use
// unused ports on your machine.
public static int clientPort = 50000;
public static int serverPort = 50001;
public static DatagramSocket ds;
public static void dgServer() throws IOException {
byte[] buffer;
String str;
BufferedReader conin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters. Enter 'stop' to quit.");
for(;;) {
// read a string from the keyboard
str = conin.readLine();
// convert string to byte array for transmission
buffer = str.getBytes();
// send a new packet that contains the string
ds.send(new DatagramPacket(buffer, buffer.length,InetAddress.getLocalHost(), clientPort));
// quit when "stop" is entered
if(str.equals("stop")) {
System.out.println("Server Quits.");
return;
}
}
JAVA PROGRAMMING
UNIT-IV 30 KNREDDY
}
public static void main(String[] args) {
ds = null;
try {
ds = new DatagramSocket(serverPort);
dgServer();
} catch(IOException exc) {
System.out.println("Communication error: " + exc);
} finally {
if(ds != null) ds.close();
}
}
}
import java.net.*;
import java.io.*;
class DGClient {
// This ports was choosen arbitrarily. You must use
// an unused port on your machine.
public static int clientPort = 50000;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static void dgClient() throws IOException {
String str;
byte[] buffer = new byte[buffer_size];
System.out.println("Receiving Data");
for(;;) {
// create a new packet to receive the data
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
// wait for a packet
ds.receive(p);
// convert buffer into String
str = new String(p.getData(), 0, p.getLength());
// display the string on the client
System.out.println(str);
// quit when "stop" is received.
if(str.equals("stop")) {
System.out.println("Client Stopping.");
break;
}
}
}
public static void main(String[] args) {
ds = null;
try {
ds = new DatagramSocket(clientPort);
dgClient();
} catch(IOException exc) {
System.out.println("Communication error: " + exc);
} finally {
if(ds != null) ds.close();
}
}
}
JAVA PROGRAMMING