You are on page 1of 46

Network Programming in

Java
Agenda
 Introduction
 Elements of Client Server Computing
 Networking Basics
 Understanding Ports and Sockets
 Java Sockets
 Implementing a Server
 Implementing a Client
 Sample Examples
 Conclusions

Usha Batra 2
Introduction
 Internet and WWW have emerged as global
ubiquitous media for communication and
changing the way we conduct science,
engineering, and commerce.
 They also changing the way we learn, live,
enjoy, communicate, interact, engage, etc.
It appears like the modern life activities are
getting completely centered around the
Internet.

Usha Batra 3
Internet Applications Serving Local
and Remote Users

PC client

Internet
Server
Local Area Network

PDA
Usha Batra 4
Increased demand for Internet
applications
 To take advantage of opportunities presented by
the Internet, businesses are continuously seeking
new and innovative ways and means for offering
their services via the Internet.
 This created a huge demand for software
designers with skills to create new Internet-
enabled applications or migrate existing/legacy
applications on the Internet platform.
 Object-oriented Java technologies—Sockets,
threads, RMI, clustering, Web services-- have
emerged as leading solutions for creating
portable, efficient, and maintainable large and
complex Internet applications.
Usha Batra 5
Elements of C-S Computing
a client, a server, and network

t
es
qu
Re
Client
Server
Network
Re
su
lt

Client machine
Server machine

Usha Batra 6
Networking Basics
 Applications Layer  TCP/IP Stack
 Standard apps
 HTTP
 FTP
Application
 Telnet
 User apps (http,ftp,telnet,…)
 Transport Layer Transport
 TCP (TCP, UDP,..)
 UDP
 Programming Interface: Network
 Sockets (IP,..)
 Network Layer
Link
 IP
 Link Layer (device driver,..)
 Device drivers

Usha Batra 7
Networking Basics
 TCP (Transport Control  TCP/IP Stack
Protocol) is a
connection-oriented
Application
protocol that provides
(http,ftp,telnet,…)
a reliable flow of data
between two Transport
computers. (TCP, UDP,..)
 Example applications: Network
 HTTP (IP,..)
 FTP Link
 Telnet (device driver,..)

Usha Batra 8
Networking Basics
 UDP (User Datagram  TCP/IP Stack
Protocol) is a protocol
that sends
Application
independent packets of
(http,ftp,telnet,…)
data, called
datagrams, from one Transport
computer to another (TCP, UDP,..)
with no guarantees Network
about arrival. (IP,..)
 Example applications: Link
 Clock server (device driver,..)
 Ping

Usha Batra 9
Understanding Ports
 The TCP and UDP P
o TCP
protocols use ports server
r Client
to map incoming t
data to a particular
process running on
a computer.
app app app app

port port port port


TCP or UDP
Packet
Usha Batra 10
Data port# data
Understanding Ports
 Port is represented by a positive (16-bit)
integer value
 Some ports have been reserved to support
common/well known services:
 ftp 21/tcp
 telnet 23/tcp
 smtp 25/tcp
 login 513/tcp
 User level process/services generally use
port number value >= 1024

Usha Batra 11
Sockets
 Socket is one end-point of a two way communication
link between two programs running on the network.
 Sockets provide an interface for programming networks
at the transport layer.
 Network communication using Sockets is very much
similar to performing file I/O
 In fact, socket handle is treated like file handle.
 The streams used in file I/O operation are also
applicable to socket-based I/O
 Socket-based communication is programming language
independent.
 That means, a socket program written in Java language
can also communicate to a program written in Java or
non-Java socket program.

Usha Batra 12
Socket Communication
 A server (program) runs on a specific
computer and has a socket that is
bound to a specific port. The server
waits and listens to the socket for a
client to make a connection request.

Connection request
port

server
Client

Usha Batra 13
Socket Communication
 If everything goes well, the server accepts the
connection. Upon acceptance, the server gets a new
socket bounds to a different port. It needs a new
socket (consequently a different port number) so that
it can continue to listen to the original socket for
connection requests while serving the connected
client.
port

server

port
Client
port Connection

Usha Batra 14
Sockets and Java Socket Classes

 A socket is an endpoint of a two-way


communication link between two programs
running on the network.
 A socket is bound to a port number so that
the TCP layer can identify the application
that data destined to be sent.
 Java’s .net package provides two classes:
 Socket – for implementing a client
 ServerSocket – for implementing a server

Usha Batra 15
Java Sockets

Server ServerSocket(1234)

Output/write stream Client

Input/read stream
Socket(“128.250.25.158”, 1234)
Usha Batra 16

It can be host_name like “usha.cs.itmindia.edu”


Implementing a Server
1. Open the Server Socket:
ServerSocket S=new ServerSocket(8189);
2. Wait for the Client Request:
Socket incoming = S.accept();
3. Create I/O streams for communicating to the client
BufferedReader in=new BufferedReader(new
InputStreamReader(incoming.getInputStream());

Printwriter out=new
PrintWriter(incoming.getOutputStream(),true);
4. Perform communication with client
5. Close sockets: client.close();

For multithreaded server:


while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter (the thread creates streams
(as in step (3) and does communication as stated in (4). Remove thread once
service is provided.
}
Usha Batra 17
Implementing a Client
1. Create a Socket Object:
client = new Socket(server, port_id );
2. Create I/O streams for communicating
with the server.
BufferedReader in=new BufferedReader(new
InputStreamReader(incoming.getInputStream());

Printwriter out=new
PrintWriter(incoming.getOutputStream(),true);
3. Perform I/O or communication with the
server:
4. Close the socket when done:
client.close();

Usha Batra 18
A simple server (simplified code)
// SimpleServer.java: a simple server program
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}

Usha Batra 19
A simple client (simplified code)
// SimpleClient.java: a simple client program
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1234
Socket s1 = new Socket(“usha”,1234);
// Get an input file handle from the socket and read the input
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());
System.out.println(st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}

Usha Batra 20
Run
 Run Server on mundroo.cs.mu.oz.au
 [usha.cs@itmindia.edu] java SimpleServer &

 Run Client on any machine (including mundroo):


 [usha.cs@itmindia.edu] java SimpleClient
Hi there

 If you run client when server is not up:


 [usha.cs@itmindia.edu] sockets [1:147] java SimpleClient
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120)
at java.net.Socket.<init>(Socket.java:273)
at java.net.Socket.<init>(Socket.java:100)
at SimpleClient.main(SimpleClient.java:6)

Usha Batra 21
Socket Exceptions
try {
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe)
{ System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}

Usha Batra 22
ServerSocket & Exceptions
 public ServerSocket(int port) throws IOException
 Creates a server socket on a specified port.
 A port of 0 creates a socket on any free port. You can use
getLocalPort() to identify the (assigned) port on which this
socket is listening.
 The maximum queue length for incoming connection
indications (a request to connect) is set to 50. If a
connection indication arrives when the queue is full, the
connection is refused.
 Throws:
 IOException - if an I/O error occurs when opening the
socket.
 SecurityException - if a security manager exists and its
checkListen method doesn't allow the operation.

Usha Batra 23
Server in Loop: Always up
// SimpleServerLoop.java: a simple server program that runs forever in a single thead
import java.net.*;
import java.io.*;
public class SimpleServerLoop {
public static void main(String args[]) throws IOException {
// Register service on port 1234
ServerSocket s = new ServerSocket(1234);
while(true)
{
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
// Send a string!
dos.writeUTF("Hi there");
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}
}

Usha Batra 24
Conclusion
 Programming client/server applications
in Java is fun and challenging.
 Programming socket programming in
Java is much easier than doing it in
other languages such as C.
 Keywords:
 Clients, servers, TCP/IP, port number,
sockets, Java sockets

Usha Batra 25
Making URL Connections

Usha Batra 26
URL
 The URL class is the simplest way for a Java program to
locate and retrieve data from the network.
 URL identifies a resource by specifying its access
protocol, network location and name. e.g.
http://www.wrox.com/index.jsp
 The java.net.URL class is an abstraction of a URL. It
extends java.lang.object, and it is a final class that can
not be subclassed.

Usha Batra 27
The URL handler Architecture
It handles two types of classes:

 Stream (Protocol) Handlers: treats the resource as a raw stream of


bytes. It is used as follows:
Java.net.URL url=new URL(“http:// …….”);
InputStream istream=url.openStream();

 Content Handlers: Here the resource is handled as an object-level


representation. It is used as follows:
Java.net.URL url=new URL(“http:// …….”);
Object ob=url.getContent();

Note: the Java URL Stream and Content handler architecture uses the
following Java classes:
Java.net.URL
Java.net.URLStreamHandler
Java.net.URLConnection
Java.net.ContentHandler

Usha Batra 28
URLConnection
URLConnection is an abstract class that represents an active
connection to a resource specified by a URL.

The URLConnection class has following purposes:


 It provides more control over the interaction with a
server than a URL class.
 With a URLConnection, you can inspect the header sent
by the server and respond accordingly.
 You can set the header fields used in the client request.
 You can use a URLConnection to download binary files.
 Finally, a URLConnection lets you send data back to a
web server with POST or PUT and use other HTTP request
methods.

Usha Batra 29
Writing a program using URLConnection class
When working with URLConnection class, then follow the following steps:

 Construct a URL object i.e.


URL url=new URL(http://..........);
 Invoke the URL object’s openConnection method of URL class to
retrieve URLConnection object for that URL:
URLConnection connection=url.openConnection();
 Set any properties using the methods:
setDoInput (by default it is true)
setDoOutput
setIfModifiedSince
setUseCaches
setAllowUserInteraction
setRequestProperty

Usha Batra 30
Writing a program using URLConnection class continue……

 Connect to remote resource by calling the “connect” method:


Connection.connect();

 After connecting to server, you can query the header


information. There are two methods, “getHeaderFieldKey” and
“getHeaderField”.
The methods available are:
getContentType
getContentLength
getContentEncoding
getDate
getExpiration
getLastModified
 Finally, access the resource data using the “getInputStream”
method.

Usha Batra 31
Example Program for showing how to use URL class
import java.io.*;
import java.net.*;
import java.util.*;

public class URLTest


{ public static void main(String[] args)
{ try{
URL url = new URL("http://www.itmindia.edu/cse/faculty.txt");
InputStream uin = url.openStream();
BufferedReader in = new BufferedReader(newInputStreamReader(uin));
boolean more = true;
while (more)
{
String line = in.readLine();
if (line == null) more = false;
else
System.out.println(line);
}

}
catch (IOException exception)
{ System.out.println("Error: " + exception);
}
}
}

Usha Batra 32
Example Program for showing how to use
URLConnection class
/* There are several methods in the URLConnection class that can be used
to set the properties of the connection before connecting to the server.

By default, the connection yields an input stream for reading from the
server but no output stream for writing. If you want to have an output
stream (for example, for posting data to a web server), then you need
to call connection.setDoOutput(true);
*/

import java.io.*;
import java.net.*;
import java.util.*;

public class URLConnectionTest


{ public static void main(String[] args)
{ try
{ String urlName;
if (args.length > 0)
urlName = args[0];
else
urlName = "http://www.yahoo.com";

URL url = new URL(urlName);

Usha Batra 33
URLConnection connection = url.openConnection();
connection.connect();
// print header fields
int n = 1;

String key;
while ((key = connection.getHeaderFieldKey(n)) != null)
{ String value = connection.getHeaderField(n);
System.out.println(key + ": " + value);
n++;
}
// print convenience functions

System.out.println("----------");
System.out.println("getContentType: "+connection.getContentType());
System.out.println("getContentLength: "+ connection.getContentLength());
System.out.println("getContentEncoding: "+connection.getContentEncoding());
System.out.println("getDate: "+ connection.getDate());
System.out.println("getExpiration: " + connection.getExpiration());
System.out.println("getLastModifed: "+ connection.getLastModified());
System.out.println("----------");

Usha Batra 34
BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));

// print first ten lines of contents

String line;
n = 1;
while ((line = in.readLine()) != null && n <= 10)
{ System.out.println(line);
n++;
}
}
catch (IOException exception)
{ System.out.println("Error: " + exception);
}
}
}

Usha Batra 35
Java Mail Messaging System

Usha Batra 36
E-Mail Messaging System
 Java e-mail messaging system is composed of mail
clients and mail servers.
 An e-mail client is a GUI based application installed on
user’s machine. The most popular are netscape
communication and MS outlook.
 An e-mail server is responsible for routing messages to
their destination and also storing messages until the
user receives them.
 SMTP defines the process for sending e-mail in a reliable
and efficient manner.
 POP3 defines mechanism for retrieving messages from a
mail server. The POP3 protocol identifies the user and
the password and retrieves only those messages for the
given user.

Usha Batra 37
Process of E-Mail Transmission

E-mail Sender SMTP Server

messages

E-mail Recipient POP3 Server

Usha Batra 38
Anatomy of an E-mail Message
 An e-mail message is composed of two major sections.
Headers containing a set of attributes and body( content).

 The header contains the information about the message, such


as the sender, recipient, subject and time stamp.
 The actual content of the message is contained in the body
part.

Message

Header Sender,
recipient,
Attributes
subject

Content
(Body)

Usha Batra 39
Sending E-Mail Manually
 In order to send and receive e-mail message you need
to have a network access to an SMTP server and a POP3
server.
 The SMTP protocol defines a collection of commands to
send your own e-mail message:
SMTP Command Description
HELO identifies the domain of the sending host such
as itmindia.edu
MAIL name of sender
RCPT name of receiver
DATA Message body of e-mail

 We can use telnet command to communicate with


SMTP server listening on port 25.

e.g. c:\Java Programs\unit 2>telnet smtp.mymailserver.com 25

Usha Batra 40
 Connected to SMTP server

HELO itmindia.edu

Smtp.mymailserver.com

MAIL from: usha.cs@itmindia.edu

Sender <usha.cs@itmindia.edu> ok

RCPT To: rimpy.it@itmindia.edu

Recipient < rimpy.it@itmindia.edu> ok

Data
Ok send data ending with .
Subject: lecture notes

Hi rimpy!
Pls. find the lecture notes.
Cheers!
.
Message received
Quit
Smtp.mymailserver.com
Connection to host lost

Usha Batra 41
Example Program
import javax.mail.*;
import javax.mail.internet.*;
/*The javax.mail API uses a properties file for reading server names
and related configuration. */

public class QuickMailText {

/**
* Sends a simple text e-mail message.
*
* smtpHost name of the SMTP mail server
* from e-mail address of the sender
* to e-mail address of the recipient
* subject subject of the e-mail message
* messageText the actual text of the message
* javax.mail.MessagingFormatException problems sending
message
*/
public static void sendMessage(String smtpHost,String from,
String to,String subject, String messageText)
throws MessagingException {

Usha Batra 42
// Step 1: Configure the mail session

System.out.println("Configuring mail session for: " + smtpHost);


java.util.Properties props = new java.util.Properties();

props.put("mail.smtp.host", smtpHost);
Session mailSession = Session.getDefaultInstance(props);

/* The Session class represents a mail session and is not subclassed. It collects together
properties and defaults used by the mail API's. Get the default Session object. */

// Step 2: Construct the message

System.out.println("Constructing message - from=" + from + " to=" + to);


InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
testMessage.setSentDate(new java.util.Date());
testMessage.setSubject(subject);
testMessage.setText(messageText);
System.out.println("Message constructed");

/* Class MimeMessage
java.lang.Object
javax.mail.Message
javax.mail.internet.MimeMessage
This class represents a MIME style email message. It implements the Message
abstract class and the MimePart interface.
Clients wanting to create new MIME style messages will instantiate an empty
MimeMessage object and then fill it with appropriate attributes and content. */

Usha Batra 43
// Step 3: Now send the message

Transport.send(testMessage);
System.out.println("Message sent!");
}

public static void main(String[] args) {


if (args.length != 3) {
System.out.println("Usage: java QuickMailText <smtphost> <from> <to>");
System.exit(1);
}
String smtpHost = args[0];
String from = args[1];
String to = args[2];
String subject = "Test Message - quickmail_text";
StringBuffer theMessage = new StringBuffer();
theMessage.append("Hello,\n\n");
theMessage.append("Hope all is well.\n");
theMessage.append("Cheers!");
try {
QuickMailText.sendMessage(smtpHost, from, to, subject,
theMessage.toString());
}
catch (javax.mail.MessagingException exc) {
exc.printStackTrace();
}
}}

Usha Batra 44
Running Java Mail API Programs
(A) Sending E-Mail
---------------
c:\>java <programname> <smtphost> <from> <to>

OR

java <programname> <smtphost> <from> <to> <filetoattach>

For example,

java QuickMailText mail.itmindia.edu usha.cs@itmindia.edu rimpy@itmindia.edu

OR

java QuickMailAttach mail.itmindia.edu usha.cs@itmindia.edu rimpy@itmindia.edu a.html

(2) To run on the Internet, type

java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90 <programname> 192.168.0.1


usha.cs@itm.edu rimpy@bits.edu

OR

java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90 <programname> 192.168.0.1


usha.cs@itm.edu rimpy@bits.edu a.html

Usha Batra 45
(B) Retrieving all E-Mails

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


<programname> <pop3host> <user> <password>

For example,

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90 MessageList


192.168.0.1 usha abc

(C) Viewing Message Contents of an E-Mail


-------------------------------------

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90


<programname> <pop3host>
<user> <password> <messagenumber>

For example,

c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90 MessageView


192.168.0.1 usha abc 2

Usha Batra 46

You might also like