You are on page 1of 14

Network Programming Unit 5

Unit 5
Network Programming
Networking Basics
Computers running on the Internet communicate to each other using either the
Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as this
diagram illustrates:

When we write Java programs that communicate over the network, we are programming
at the application layer. We don't need to concern ourselves with the TCP and UDP
layers. Instead, we can use the classes in the java.net package. These classes provide
system independent network communication. However, to decide which Java classes
your programs should use, we need to understand how TCP and UDP differ.

TCP
TCP is a connection-based protocol that provides a reliable flow of data between two
computers. When two applications want to communicate to each other reliably, they
establish a connection and send data back and forth over that connection. This is
analogous to making a telephone call. If Ram (Katmandu) want to speak to Hari
(Pokhara), a connection is established when Ram dials his phone number and Hari
answers. Ram and Hari send data back and forth over the connection by speaking to one
another over the phone lines. Like the phone company, TCP guarantees that data sent
from one end of the connection actually gets to the other end and in the same order it was
sent. Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable
communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP),
and Telnet are all examples of applications that require a reliable communication
channel. The order in which the data is sent and received over the network is critical to
the success of these applications. When HTTP is used to read from a URL, the data must
be received in the order in which it was sent. Otherwise, you end up with a jumbled
HTML file, a corrupt zip file, or some other invalid information.

Page 1
Network Programming Unit 5

UDP
UDP is a protocol that sends independent packets of data, called datagrams, from one
computer to another with no guarantees about arrival. UDP is not connection-based like
TCP.
The UDP protocol provides for communication that is not guaranteed between two
applications on the network. UDP is not connection-based like TCP. Rather, it sends
independent packets of data, called datagrams, from one application to another. Sending
datagrams is much like sending a letter through the postal service. The order of delivery
is not important and is not guaranteed, and each message is independent of any other.
For many applications, the guarantee of reliability is critical to the success of the
transfer of information from one end of the connection to the other. However, other forms
of communication don't require such strict standards.

Understanding Ports
The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer.
Generally speaking, a computer has a single physical connection to the network. All
data destined for a particular computer arrives through that connection. However, the data
may be intended for different applications running on the computer. So how does the
computer know to which application to forward the data? This is done through the use of
ports.
Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined. The computer is identified by
its 32-bit IP address. Ports are identified by a 16-bit number, which TCP and UDP use to
deliver the data to the right application.
Port numbers range from 0 to 65,535 because ports are represented by 16-bit
numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use
by well-known services such as HTTP and FTP and other system services. These ports
are called well-known ports. Your applications should not attempt to bind to them.
In connection-based communication such as TCP, a server application binds a socket
(software interfaces that connect an application to a network) to a specific port number.
This has the effect of registering the server with the system to receive all data destined for
that port. A client can then communicate with the server at the server's port, as illustrated
here:

In datagram-based communication such as UDP, the datagram packet contains the port
number of its destination and UDP routes the packet to the appropriate application, as
illustrated in this figure:

Page 2
Network Programming Unit 5

Networking Classes in the JDK


Through the classes in java.net, Java programs can use TCP or UDP to communicate
over the Internet. The URL, URLConnection, Socket, and ServerSocket classes
all use TCP to communicate over the network. The DatagramPacket,
DatagramSocket, and MulticastSocket classes are for use with UDP. This
package also contains other additional classes that are useful in network programming.

Working with URLs


URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a
resource on the Internet. You provide URLs to your favorite Web browser so that it can
locate files on the Internet in the same way that you provide addresses on letters so that
the post office can locate your correspondents.
Java programs that interact with the Internet also may use URLs to find the resources
on the Internet they wish to access. Java programs can use a class called URL in the
java.net package to represent a URL address.
A URL has two main components: protocol identifier and resource name. For
example, https://oracle.com; here https is protocol identifier and oracle.com is resource
name. Note that the protocol identifier and the resource name are separated by a colon
and two forward slashes.
The easiest way to create a URL object is from a String that represents the human-
readable form of the URL address. This is typically the form that another person will use
for a URL. For example,
URL url1 = new URL("https://oracle.com");
The URL class provides several methods that let you query URL objects. You can get the
protocol, authority, host name, port number, path, query, filename, and reference from a
URL using these accessor methods:
 getProtocol - Returns the protocol identifier component of the URL.
 getAuthority - Returns the authority component of the URL.
 getHost - Returns the host name component of the URL.
 getPort - Returns the port number component of the URL. The getPort method
returns an integer that is the port number. If the port is not set, getPort returns -1.
 getPath - Returns the path component of this URL.

Page 3
Network Programming Unit 5

 getQuery - Returns the query component of this URL.


 getFile - Returns the filename component of the URL. The getFile method returns
the same as getPath, plus the concatenation of the value of getQuery, if any.
 getRef - Returns the reference component of the URL.
Note: Remember that not all URL addresses contain these components. The URL class
provides these methods because HTTP URLs do contain these components and are
perhaps the most commonly used URLs.
Example:
import java.net.*;
public class URLDemo
{
public static void main(String[] args)
{
try
{
URL aURL = new URL("https://www.oracle.com:80/java/technologies/javase-
downloads.html");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
catch(MalformedURLException e)
{
System.out.println(e);
}
}
}

Reading Directly from the URL


After you've successfully created a URL, you can call the URL's openStream() method to
get a stream from which you can read the contents of the URL. For example,
import java.net.*;
import java.io.*;
public class ReadingURL
{
public static void main(String[] args)
{
try
{
URL aURL = new URL("https://www.oracle.com/java/technologies/javase-

Page 4
Network Programming Unit 5

downloads.html");
BufferedReader in = new BufferedReader(new
InputStreamReader(aURL.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch(MalformedURLException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Connecting to a URL
After you've successfully created a URL object, you can call the URL object's
openConnection method to get a URLConnection object. You can use this
URLConnection object to setup parameters and general request properties that you
may need before connecting. Connection to the remote object represented by the URL is
only initiated when the URLConnection.connect method is called. When you do
this you are initializing a communication link between your Java program and the URL
over the network. For example,
import java.net.*;
import java.io.*;
public class ConnectingURL
{
public static void main(String[] args)
{
try
{
URL aURL = new URL("https://www.oracle.com/java/technologies/javase-
downloads.html");
URLConnection connection = aURL.openConnection();
connection.connect();
}
catch (MalformedURLException e)
{
System.out.println(e);
}
catch(IOException e)

Page 5
Network Programming Unit 5

{
System.out.println(e);
}
}
}
Now that you've successfully connected to your URL, you can use the
URLConnection object to perform actions such as reading from or writing to the
connection.

The InetAddress Class


The InetAddress class in java.net package is used to encapsulate both the numerical IP
addresses and the domain name for that address. You interact with this class by using the
name of an IP host, which is more convenient and understandable than its IP address. To
create an InetAddress object, you have to use one of the following methods:
 getLocalHost() – simply returns the InetAddress object that represents the local
host.
 getByName(String hostName) – returns an InetAddress object for a host name
passed to it.
 getAllByName(String hostname) – returns an array of InetAddress objects that
represent a host name passed to it.
For example,
import java.net.*;
class InetAddressTest {
public static void main(String[]args) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("yahoo.com");
System.out.println(address);
InetAddress addr[] = InetAddress.getAllByName("yahoo.com");
for(int i = 0; i<addr.length; i++)
System.out.println(addr[i]);
}
}
The InetAddress class also has several other methods, which can be used on the objects
returned by above methods. Some of the most commonly used are:
 equals(Object other) – returns true if this object has the same Internet address as
other.
 getAddress() – returns a byte array that represents the object’s Internet address.
 getHostAddress() – returns a string that represents the host address associated
with the object.
 getHostName() – returns a string that represents the host name associated with
the object.

Page 6
Network Programming Unit 5

 isMulticastAddress() – returns true id this internet address is a multicast address.


Otherwise it returns false.
 toString() – returns a string that lists the host name and the IP address for
convenience.

Sockets
A socket is an endpoint of a two-way communication link between two programs
running on the network. Sockets constitute a mechanism for delivering incoming data
packets to the appropriate application based on a combination of local and remote IP
addresses and port numbers. A socket address is the combination of an IP address, and a
port into a single identity. IP address represents the location of the computer and port
address represents the application program process in that location.
Basically, there are two types of sockets: datagram sockets and stream sockets.
Datagram sockets are also known as connectionless sockets and use user datagram
protocol (UDP). Stream sockets are also known as connection-oriented sockets and use
transmission control protocol (TCP).

TCP Sockets
There are two kinds of TCP sockets in Java. One is for servers and the other is for clients.
The ServerSocket class is designed to a “listener” which waits for clients to connect
before doing anything. The Socket class is designed to connect to server sockets.
The creation of a Socket object implicitly establishes a connection between the client
and server. We can use the following two constructors to create client sockets:
 Socket(String hostName, int port) – creates a socket connecting the local host to
the named host and port; can throw an UnknownHostException or an
IOException.
 Socket(InetAddress ipAddress, int port) – creates a socket using the preexisting
InetAddress object and a port; can throw an IOException.
A socket can be examined at any time for the address and port information associated
with it, by use of the following methods:
 getInetAddress() – returns the InetAddress associated with the Socket object.
 getPort() – returns the remote port to which the invoking Socket object is
connected.
 getLocalPort() – returns the local port to which the invoking Socket object is
connected.
Once the Socket object has been created, it can also be examined to gain access to the
input and output streams associated with it. Each of the following methods can throw an
IOException if the sockets have been invalidated by loss of connection on the Net.
 gerInputStream() – returns the InputStream object associated with the invoking
socket.
 getOutputStream() – returns the OutputStream object associated with the
invoking socket.

Page 7
Network Programming Unit 5

Example (Client Program)


import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[]args) {
System.out.println("TCP client initialized....");
try {
Socket s = new Socket("localhost", 19999);
OutputStream out = s.getOutputStream();
String str = "How are you?" + (char)13;
byte buf[] = str.getBytes();
out.write(buf);
out.flush();
InputStream in = s.getInputStream();
int c;
while ( (c = in.read()) != 13)
System.out.print((char)c);
System.out.println();
in.close();
out.close();
s.close();
} catch (IOException f) {
System.out.println("IOException: " + f);
}
}
}
The ServerSocket class is used to create servers that listen for client programs to connect
to them on published ports. ServerSockets are quite different from normal Sockets. When
you create a ServerSocket, it will register itself with the system as having an interest in
client connections. The constructors for ServerSocket reflect the port number that you
wish to accept connections on and, optionally, how long you want the queue for said port
to be. The queue length tells the system how many client connections it can leave
pending before it should simply refuse connections. The default is 50. The constructors
might throw an IOException under adverse conditions. These constructors are given
below:
 ServerSocket(in port) – creates server socket on the specified port with a queue
length of 50;
 ServerSocket(int port, in maxQueue) – creates a server socket on the specified
port with a maximum queue length of maxQueue.
 ServerSocket(int port, int maxQueue, InetAddress localAddress) – creates a
server socket on the specified port with a maximum queue length of maxQueue.
On a multimode host, localAddress specifies the IP address to which this socket
binds.

Page 8
Network Programming Unit 5

Example (Server Program)


import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) {
System.out.println("TCP server Initialized.....");
try {
ServerSocket ss = new ServerSocket(19999);
Socket s = ss.accept();
InputStream in = s.getInputStream();
int c;
while ((c = in.read()) != 13)
System.out.print((char)c);
System.out.println();
OutputStream out = s.getOutputStream();
String str = "I am fine" + (char) 13;
byte buf[] = str.getBytes();
out.write(buf);
out.flush();
in.close();
out.close();
s.close();
ss.close();
} catch (IOException f) {
System.out.println("IOException: " + f);
}
}
}

Datagram Sockets
The UDP protocol provides a mode of network communication whereby applications
send packets of data called datagrams to one another. A datagram is an independent, self-
contained message sent over the network whose arrival, arrival time, and content are not
guaranteed. The DatagramPacket and DatagramSocket classes in the
java.net package implement system-independent datagram communication using
UDP.
The DatagramSocket class represents a socket for sending and receiving
datagaram packets. It is the sending or receiving point for a packet delivery service. Each
datagram sent or received on a datagram socket is individually addressed and routed.
Some of its useful constructors are:
 DatagramSocket() – constructs a datagram socket and binds it to any available
port.
 DatagramSocket(int port) – constructs a datagram socket with the specified
port.

Page 9
Network Programming Unit 5

 DatagramSocket(int port, InetAddress address) – constructs a datagram socket


to the specified port and address.
The DatagramPacket class represents an object for data container. The
DatagramPacket defines several useful constructors. Two of them are described here.
 DatagramPacket(byte data[], int size) – specifies a buffer that will receive data,
and the size of a packet. It is used for receiving data over a DatagramSocket.
 DatagramPacket(byte data[], int size, InetAddress ipAddress, int port) –
specifies a target address and port, which are used by a DatagramSocket to
determine where the data in the packet will be sent.
There are several methods for accessing the internal state of a DatagramPacket.
Some of its most commonly used methods are:
 getAddress() – returns the InetAddress, typically used when sending.
 getPort() – returns the port number as integer value.
 getData() – returns the byte array of data contained in the datagram. Mostly used
to retrieve data from the datagram after it has been received.
 getLength() – returns the length of the valid data contained in the byte array that
would be returned from the getData() method. This typically does not equal the
length of the whole byte array.
Example (Client Program)
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
System.out.println("UDP client initialized....");
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
byte[]sendData = new byte[1024];
byte[]receiveData = new byte[1024];
String str = "How are you?";
sendData = str.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, address, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String received = new String(receivePacket.getData());
System.out.println(received.trim());
clientSocket.close();
} catch (IOException f) {
System.out.println("IOException: " + f);
}
}

Page 10
Network Programming Unit 5

Example (Server Program)


import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
System.out.println("UDP server initialized....");
try {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[]sendData = new byte[1024];
byte[]receiveData = new byte[1024];
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String received = new String(receivePacket.getData());
System.out.println(received.trim());
InetAddress address = receivePacket.getAddress();
int port = receivePacket.getPort();
String str = "I am fine";
sendData = str.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, address, port);
serverSocket.send(sendPacket);
serverSocket.close();
} catch (IOException f) {
System.out.println("IOException: " + f);
}
}
}

Java Mail API


The JavaMail API provides a platform-independent and protocol-independent framework
to work with emails, providing access to email systems. We can use this API to create,
send, and receive email messages. The JavaMail API is made up of four packages. These
packages are:
 javax.mail – provides the core classes for the generating, sending and reading
email.
 javax.mail.event – event listeners and associated events for notifying application
classes of mail related activities.
 javax.mail.internet – classes specific to Internet mail systems including MIME
type emails.
 javax.mail.search – provides for searching through emails during the process of
retrieving emails form a server centric email system.

Page 11
Network Programming Unit 5

It is important to realize that the JavaMail API focuses on eMail user Agent type
programs such as Eudora and not on implementing an email server. Thus the API
provides for reading, constructing, and sending electronic messages via a server that
understands an email protocol such as SMTP or POP. SMTP stands for Simple Mail
Transfer Protocol (SMTP) which is the protocol most often used to send email. POP
stands for Post Office Protocol (currently in version 3 and often referred to as POP3)
which is the protocol most often used to receive email.

Sending Email
The steps that we must follow to create an email and send it are:
1. Create and initialize a session object.
2. Create and put message into a message object.
3. Send the message.
To send email, the first step is to create a Properties object and store properties in it. Next
we create an instance of the Session object. This can be done using the factory method
getDefaultInstance. This method takes two parameters: the properties indicating which
mail sererver to use and an authenticator objet if one is being used.
Next, we need to create a message object suitable for the mail system in use. After
that we need to set up a number of attributes for the message such as who sent the
message and where it should go etc. We now have an email message which is ready to be
sent to the recipient.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail
{
public static void main(String[] args)
{
String to = "nawarajpaudel@yahoo.com";
String from = "nawarajpaudel.np@gmail.com";
String host = "smtp.gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.auth", "true");
Session ses = Session.getInstance(props, new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, "****");
}
});
ses.setDebug(true);
try

Page 12
Network Programming Unit 5

{
MimeMessage msg = new MimeMessage(ses);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("Hello");
msg.setText("How are you these days.");
System.out.println("sending...");
Transport.send(msg);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}

Receiving Messages
So far we have focused on sending emails. The other aspect of an email tool is receiving
emails. JavaMail API provides for reading emails from an email server. Just as with
sending emails the starting point is the Session object. However we do not need to define
any specific properties.
When reading email we have to get hold of a store object. The store object obtained
must be appropriate for the specific protocol. A store is an object that models a message
store and its access protocol, for storing and retrieving messages. Once the store object
has been obtained it is necessary to connect the store to the email server that will supply
email messages.
We are now in a position to be able to obtain a Folder object that will supply the
actual email messages. A POP3 server only has one folder, the “INBOX” folder. This
folder holds the emails held on the email server that have not been downloaded yet. To
actually download the messages it is necessary to open the folder.
You can retrieve the messages using the method getMessage() on the folder object.
This returns an array of Message objects. Finally you have to close the folder and store.
import java.util.*;
import javax.mail.*;
public class ReceiveMail
{
public static void main(String[] args)
{
String host = "pop.gmail.com";
String uname = "nawarajpaudel.np@gmail.com";
String pwd = "******";
try
{
Properties props = new Properties();

Page 13
Network Programming Unit 5

Session ses = Session.getDefaultInstance(props);


Store st = ses.getStore("pop3s");
st.connect(host, uname, pwd);
Folder fol = st.getFolder("INBOX");
fol.open(Folder.READ_ONLY);
Message[] msg = fol.getMessages();
for (int i = 0, n = msg.length; i < n; i++)
{
System.out.println("Printing individual messages");
System.out.println("No# " + (i + 1));
System.out.println("Email Subject: " + msg[i].getSubject());
System.out.println("Sender: " + msg[i].getFrom()[0]);
System.out.println("Content: " + msg[i].getContent().toString());
}
fol.close(false);
st.close();
}
catch (NoSuchProviderException exp)
{
exp.printStackTrace();
}
catch (MessagingException exp)
{
exp.printStackTrace();
}
catch (Exception exp)
{
exp.printStackTrace();
}
}
}

Page 14

You might also like