Professional Documents
Culture Documents
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
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
Usha Batra 15
Java Sockets
Server ServerSocket(1234)
Input/read stream
Socket(“128.250.25.158”, 1234)
Usha Batra 16
Printwriter out=new
PrintWriter(incoming.getOutputStream(),true);
4. Perform communication with client
5. Close sockets: client.close();
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 &
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:
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.
Usha Batra 29
Writing a program using URLConnection class
When working with URLConnection class, then follow the following steps:
Usha Batra 30
Writing a program using URLConnection class continue……
Usha Batra 31
Example Program for showing how to use URL class
import java.io.*;
import java.net.*;
import java.util.*;
}
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.*;
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()));
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
messages
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).
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
Usha Batra 40
Connected to SMTP server
HELO itmindia.edu
Smtp.mymailserver.com
Sender <usha.cs@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. */
/**
* 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
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. */
/* 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!");
}
Usha Batra 44
Running Java Mail API Programs
(A) Sending E-Mail
---------------
c:\>java <programname> <smtphost> <from> <to>
OR
For example,
OR
OR
Usha Batra 45
(B) Retrieving all E-Mails
For example,
For example,
Usha Batra 46