Java
Java
Rajkumar Buyya
School of Computer Science and Software Engineering
Monash University
Melbourne, Australia
Email: rajkumar@dgs.monash.edu.au
URL: http://www.dgs.monash.edu.au/~rajkumar
1
Agenda
(c) Rajkumar
3
Internet Technology
Evolution
(c) Rajkumar
❃ Use of internet
advertisement/elections/newspapers
❃ information is public
❃ Ubiquitous technology
❃ Network is the computer
❃ Intranets - internal TCP/IP nets
❃ PC accounts for 55% of total IT
❃ Applications tied to platform - API
lock-in
5
Internet Evolution
(c) Rajkumar
Internet everywhere
Internet appliances
On line connects Price based services
to internet Live communities
File & mail Secure payments ?
TCP/IP Multi media Authoring ?
Webpages Java ?
Netscape VRML ?
HTML ?
?
10% of ?
20% of Total
Market
Market Market
6
Early
Internet
(c) Rajkumar
7
World Wide Web
(c) Rajkumar
8
HTML
(c) Rajkumar
9
Internet Tools
(c) Rajkumar
10
How does the Web work
?
(c) Rajkumar
❃ Web -Designed around Client/Server Architecture
❃ Web Clients ( Web Browsers ) -send requests for
documents to any Web Server
❃ Web Server -Program that responds to HTTP requests
❃ Hyperlink
❃ Web client connects to the specified Web Server
❃ The server responds by sending the information asked
for
❃ The Browser formats the received HTML data and
displays it
11
How does the Web Work
(c) Rajkumar Send
Sendthe
the“INFORMATION
“INFORMATIONABOUT
ABOUT C-DAC
C-DACACTS”
ACTS”
HTTP
The
Theclient
clientsends
sendsan
anHTTP
HTTPmessage
messagetotoaacomputer
computer
running
running a Web Server program and asks foraadocument
a Web Server program and asks for document
The information
about
C-DAC ACTS
The
Theweb
webserver
serversends
sendsthe
thehypermedia
hypermediaHTML
HTMLdocuments
documentstotothe
theclient.
client.
You
Youend
endup
upseeing
seeingthe
thedocument
documenton
onyour
yourscreen
screen 12
HTML document
(c) Rajkumar
<HTML>
<TITLE>Centre for Development of Advanced Computing
</TITLE>
<BODY BGCOLOR=“#E7CCCC” TEXT=“#000000”
LINK=“#0000FF”>
...
...
<A HREF=“mailto:webmaster@cdacb.ernet.in>
webmaster</A>
</BODY>
</HTML>
13
(c) Rajkumar
14
URLs
(c) Rajkumar
15
CGI (Common Gateway
Interface)
(c) Rajkumar
16
Authoring tools and
Filters
(c) Rajkumar
17
Preconfigured v/s
Integrated Internet
Products
(c) Rajkumar
18
Future Directions
(c) Rajkumar
19
Interesting URLs
(c) Rajkumar
❃ http://www.whitehouse.gov ( The WhiteHouse)
❃ http://www.w3.org (Everything about the WWW)
❃ http://sunsite.unc.edu (Software on Sun)
❃ http://www.indnet.org (India Net Foundation Services)
❃ telnet://www.arbornet.org (Free Public Access Unix System)
❃ http://www.infoseek.com (Search engines, Add URL)
❃ http://www.infophil.com (World Alumni on the net)
❃ http://www.rocketmail.com (Free Email )
❃ http://members.tripod.com (Free Website,2MB space)
❃ http://www.bangaloreonline.com (Offers virtual web servvices
for compinies to host their website).
❃ http://www.prajavani.com (Kannada news paper on web)
20
API Bottleneck
(c) Rajkumar
MAC
PC
LAN LAN
Server
Network
SUN
21
The OS - Platform lock
(c) Rajkumar
Applications tied to OS
Application
OS tied to Platform
n
Ap
tio
p
a
lic
lic
a tio
p
n
Ap
OS
Application Application
22
The Web
Application
(c) Rajkumar
* Seeded by HTML from CERN
* Revolutionised by MOSAIC
* Standardised, universal interface
n
to data Ap
tio
pli
a
ca
lic
tio
p
* Graphical n
Ap
BROWSER
OS OS OS OS
Application Application
* Broadcast capability -
publish once, reach millions
23
Making life easier!
(c) Rajkumar
24
Java and Java
Computing
(c) Rajkumar
25
Java - An Introduction
(c) Rajkumar
26
Java From 10,000 Ft.
(c) Rajkumar
27
According to the World,
Java Is...
(c) Rajkumar
28
According to Sun, Java
is...
(c) Rajkumar
❃ Simple and Powerful
❃ Object Oriented
❃ Portable
❃ Architecture Neutral
❃ Distributed
❃ Multi-threaded
❃ Robust, Secure/Safe
❃ Interpreted
❃ High Performance
❃ Dynamic pogramming language/platform.
Buzzword compliant!
29
On Closer Inspection,
Java is...
(c) Rajkumar
❃ Simple
❃ Pure
❃ Portable
❃ Surprisingly effective
30
As a whole, Java is a Comprehensive
Programming Solution
(c) Rajkumar
❃ Object Oriented
❃ Portable
❃ High Performance
❃ Geared for Distributed Environments
❃ Secure
31
Java as Object Oriented
(c) Rajkumar
32
Java as Portable
(c) Rajkumar
33
Total Platform Independence
(c) Rajkumar
JAVA COMPILER
(translator)
JAVA INTERPRETER
(one for each different system)
Java
35
Architecture Neutral &
Portable
(c) Rajkumar
36
Java as High
Performance
(c) Rajkumar
37
Java in the World of
Distributed Computing
(c) Rajkumar
❃ Class Loader
❃ Lightweight Binary Class Files
❃ Multithreading
❃ Dynamic
❃ Good communication constructs
❃ Secure
38
Java as Secure
(c) Rajkumar
39
Object Oriented
Languages -a
Comparison
(c) Rajkumar
Objective
Feature C++ C Ada Java
40
Java better than C++ ?
(c) Rajkumar
?
❃ No Pointers
❃ No Unsafe Structures
❃ No Multiple Inheritance
❃ No Operator Overloading
❃ No Automatic Coercions
❃ No Fragile Data Types
41
Basic Data Types
(c) Rajkumar
❃ Types
boolean either true of false
char 16 bit Unicode 1.1
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (singed)
float 32-bit floating point (IEEE 754-1985)
double 64-bit floating point (IEEE 754-1985)
❃ String (class for manipulating strings)
❃ Java uses Unicode to represent characters
internally
42
(c) Rajkumar
Java Integrates
Power of Compiled Languages
and
Flexibility of Interpreted Languages
43
Two Types of
JavaApplications
(c) Rajkumar
44
Java Environment/
Life Cycle of Java Code
(c) Rajkumar Runtime
Compile-time Environment Class
Environment Java
Loader
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java
Time
Interpreter Java
Java Compiler
Bytecodes Virtual
Java move locally machine
Compiler or through
network
Runtime System
Java
Bytecod Operating System
e
(.class )
Hardware
45
Java Development Kit
(c) Rajkumar
46
Hello Internet
(c) Rajkumar
❃ Compilation
# javac hello.java
results in HelloInternet.class
❃ Execution
# java HelloInternet
Hello Internet
#
48
Simple Java Applet
(c) Rajkumar
49
Calling an Applet
(c) Rajkumar
<HTML>
<TITLE> Hello Worls Applet </TITLE>
<APPLET code=“HelloWorld.class” width=500
height=500>
</APPLET>
</HTML>
50
Execution of Applets
(c) Rajkumar
2 4 5
1 3
APPLET hello.class Create Accessing The browser
Development AT C-DAC’S Applet from creates
“hello.java” WEB tag in CRAY Corp. a new
AT SERVER HTML (USA) window and
CDAC-India document a new thread
and
then runs the
code
Hello Java
<app=
“Hello”> The Internet
Hello
51
Web Perspective
(c) Rajkumar
52
Classical Web
Perspective
(c) Rajkumar
53
Java Web Perspective
(c) Rajkumar
54
Significance of
downloading Applets
(c) Rajkumar
❃ Interactive WWW
❃ Flashy animation instead of static web pages
❃ Applets react to users input and dynamically change
❃ Display of dynamic data
❃ WWW with Java - more than a document publishing
medium
http://www.javasoft.com/applets/alpha/applets/StockDemo/
standalone.html
55
Power of Java and the
Web
(c) Rajkumar
56
Lifecycle of Java Code
(c) Rajkumar
57
Bytecode Verifier
(c) Rajkumar
❃ Called when class is first loaded in
runtime environment
❃ Verifies bytecodes meet certain set of
properties
❃ Verifier uses Theorem Prover
❃ Verified code runs faster
❃ After verification, interpreter defines
memory layout
58
Class Loader
(c) Rajkumar
59
Security Manager
(c) Rajkumar
60
General Language
Features
(c) Rajkumar
61
Removed From C++
(c) Rajkumar
❃ Operator overloading
❃ Pointers and Array/pointers
❃ Multiple-inheritance of implementation
❃ Enum, typedef, #define
❃ Copy constructors, destructors
❃ Templates
❃ And other stuff....
62
Added or Improved over
C++
(c) Rajkumar
63
Rich Object
Environment
(c) Rajkumar
❃ Core Classes
language
Utilities
Input/Output
Low-Level Networking
Abstract Graphical User Interface
❃ Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
64
Main Packages
(c) Rajkumar
■ java.lang
■ java.util
■ java.io
■ java.awt
■ java.awt.image
■ java.applet
■ java.net
65
(c) Rajkumar
Java Fundamentals
Constructs
Graphics
Multithreading
Streams and Networking
Networking
66
Unit I--Java Constructs
(c) Rajkumar
67
Unit II--Graphics
Programming
(c) Rajkumar
68
Unit III--Advanced
Features
(c) Rajkumar
❃ Applets,
❃ Threads,
❃ Streams I/O,
❃ Networking
69
Unit I -- What is Java ?
(c) Rajkumar
❃ A programming language:
– Object oriented (no friends, all functions are
members of classes, no function libraries -- just
class libraries)
– simple (no pointer arithmetic, no need for
programmer to deallocate memory)
– platform independent
– dynamic
– interpreted
70
Types
(c) Rajkumar
71
Classes and objects
(c) Rajkumar
❃ declaring a class
class MyClass {
member variables;
…
member functions () ;
…
} // end class MyClass
72
Java programs
(c) Rajkumar
❃ Two kinds
– Applications
• have main()
• run from the OS prompt
– Applets
• have init(), start(), stop(), paint(), update(), repaint(),
destroy()
• run from within a web page
73
The first Java
Application
(c) Rajkumar
class MyApp {
public static void main(String s [ ] ) {
System.out.println(“Hello World”);
}
} // end class MyApp
74
Declaring and creating
objects
(c) Rajkumar
❃ declare a reference
– String s;
❃ create/define an object
– s = new String (“India”);
India
75
Arrays (are objects in
Java)
(c) Rajkumar
❃ declare
– int a [ ] ; // 1-dim
– int [ ] b ; // 1-dim
– int [ ] c [ ]; // 2-dim
– int c [ ][]; // 2-dim
❃ allocate space
– a = new int [7];
– c = new int [7][11];
76
Arrays have length
(c) Rajkumar
77
… this is because
(c) Rajkumar
78
… this is because
(c) Rajkumar
79
Constructors
(c) Rajkumar
80
this keyword
(c) Rajkumar
81
this :: with a variable
(c) Rajkumar
82
this :: with a method
(c) Rajkumar
83
this :: as a function inside a constructor
of “this” class
(c) Rajkumar
84
this :: as “this” object, when passed
as parameter
(c) Rajkumar
85
static keyword
(c) Rajkumar
86
static keyword (with
variables)
(c) Rajkumar
class PurchaseOrder {
private static int POCount; // var. ‘a’ is shared by all objects of this class
87
static keyword (w/
methods)
(c) Rajkumar
class Math {
public static double sqrt(double x) {
// calculate
return result;
}
}
class MyApp {
public static void main(String [] s ) {
double dd;
dd = Math.sqrt(7.11);
}
}
88
Inheritance
(subclassing)
(c) Rajkumar
class Employee {
protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
89
Manager can be made a
sub/derived-class of
Employee
(c) Rajkumar
90
Overriding (methods)
(c) Rajkumar
(c) Rajkumar
class First {
public First() { System.out.println(“ First class “); }
}
public class Second extends First {
public Second() { System.out.println(“Second class”); }
}
public class Third extends Second {
public Third() {System.out.println(“Third class”);}
}
First class
Second class
Third class
93
super keyword
(c) Rajkumar
94
super :: with a method
(c) Rajkumar
class Manager extends Employee {
private double bonus;
public void setBonus(double bb) { …}
public void raise(double dd) { //overrides raise() of
Employee
95
super :: as a function inside a constructor of
the subclass
(c) Rajkumar
96
final keyword
(c) Rajkumar
❃ means “constant”
❃ applies to
– variables (makes a var. constant), or
– methods (makes a method non-
overridable), or
– classes (makes a class non-subclassable
means “objects cannot be created”).
97
final keyword with a
variable
(c) Rajkumar
class Math {
98
final keyword with a method
(c) Rajkumar
class Employee {
protected String name;
protected double salary;
public final void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot ovveride method raise() inside
the Manager class
99
final keyword with a class
(c) Rajkumar
final class Employee {
protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot create class Manager as a
subclass of class Employee (all are equal)
100
abstract classes and
interfaces
(c) Rajkumar
❃ abstract classes
– may have both implemented and non-
implemented methods
❃ interfaces
– have only non-implemented methods
❃ (concrete classes)
– have all their methods implemented
101
sample abstract class
(c) Rajkumar abstract class TwoDimensionalGeoFigure {
public abstract double area();
public abstract double perimeter();
public abstract void printInfo();
public void setOutlineColor(Color cc) {
// code to set the color
}
public void setInsideColor(Color cc) {
// code to set the color
}
}
102
sample interface
(c) Rajkumar
interface ResponceToMouseClick {
public void mouseDown();
public void mouseUp();
public void mouseDoubleClick();
}
103
Exceptions (error
handling)
(c) Rajkumar A nice way to handle errors in Java programs
104
Exceptions (cont’d)
(c) Rajkumar ...
int a = 7, b = 0, result;
try {
result = a/b;
/// more code .. reading from a file
}
catch (ArithmeticException e ) {
System.out.println(“b is zero”);
}
catch (IOException e ) {
System.out.println(“Can’t read”);
}
finally {
Sysytem.out.println(“Closing file”);
/// code to close file
}
...
105
methods throwing exceptions
(c) Rajkumar
if (y == 0 ) {
throw new ArithmeticException();
}
else {
return a/b ;
}
} // end divide()
106
Defining your own exceptions
if (y == 0 ) {
throw new MyException();
}
else {
return a/b ;
}
} // end divide()
107
(c) Rajkumar
GUI Programming in
Java
(AWT and Event Handling)
108
AWT - Abstract
Windowing Toolkit
(c) Rajkumar
109
AWT - Abstract Window
Toolkit
(c) Rajkumar
110
Adding Components via
Layouts
(c) Rajkumar
setLayout(new BorderLayout());
// Add text field to top
add("North",new TextField());
// Create the panel with buttons at the bottom...
Panel p = new Panel(); // FlowLayout
p.add(new Button("OK"));
p.add(new Button("Cancel"));
add("South",p);
111
Adding Components via
Layouts
(c) Rajkumar
112
Building Graphical User
Interfaces
(c) Rajkumar
❃ import java.awt.*;
❃ Assemble the GUI
– use GUI components,
• basic components (e.g., Button, TextField)
• containers (Frame, Panel)
– set the positioning of the components
• use Layout Managers
❃ Attach events
113
A sample GUI program
(c) Rajkumar
Import java.awt.*;
class MyGui {
public static void main(String [] s ) {
Frame f = new Frame (“My Frame”);
Button b = new Button(“OK”);
TextField tf = new TextField(“George”, 20);
f.setLayout(new FlowLayout());
f.add(b);
f.add(tf);
f.setSize(300, 300);
f.setVisible(true);
}
}
114
output
(c) Rajkumar
115
Events
(c) Rajkumar
b.addActionListener( );
Button
method to add a listener listener object
Frame
f.addWindowListener( );
116
Events
(c) Rajkumar
117
Listener Interfaces
(c) Rajkumar
(c) Rajkumar
120
How to create an
object of a listener
interface ?
(c) Rajkumar
121
Implementing the ActionListener Interface
and attaching an event handler to a button
(c) Rajkumar
(c) Rajkumar
123
or … use Adapters
124
But, we can only use one Adapter at a time (no
multiple inheritance)
(c) Rajkumar
127
Popup Menu and Event Handling...
130
AWT & Applets
(c) Rajkumar
An Applet is a Java program capable of running from
within a web page (HTML document)
131
Applet methods
(c) Rajkumar
132
A sample Applet
133
sample Applet
(c) Rajkumar
134
another sample
Applet (run in Applet
Viewer)
(c) Rajkumar
135
sample Applet
running within Netscape
(c) Rajkumar
136
sample Applet code
(c) Rajkumar
import java.applet.*; // for Applet class
import java.awt.*; // for Graphics class
public class MyApplet extends Applet {
public void paint( Graphics g ) {
g.drawString("Hi there", 40, 40);
g.drawOval(40, 60, 45, 45);
g.drawRect(100, 60, 50, 50);
g.drawLine(170, 60, 250, 170);
} // end paint()
public void init() {
setBackground(Color.yellow);
}
} // end class MyApplet
137
Another example
(c) Rajkumar//MyApplet.java: draws rectangle with yellow color fill
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public synchronized void paint(Graphics g)
{
int x,y,width,height;
Dimension dm = size();
x = dm.width/4;
y = dm.height / 4;
width = dm.width / 2;
height = dm.height / 2;
// Draw the rectangle in the center with colors!
g.setColor(Color.blue);
g.drawRect(x,y,width,height);
g.setColor(Color.yellow);
g.fillRect(x + 1,y + 1,width - 2,height - 2);
}
}
138
order of Applet method
execution
(c) Rajkumar
139
order of Applet method
execution (cont’d)
(c) Rajkumar
141
sample Applet with
sound
(c) Rajkumar
… … … (MyAppletSound.java)
142
how to do that ….
(c) Rajkumar
143
Applet that displays image
import java.applet.*;
(c) Rajkumar
import java.awt.*;
public class MyApplet1 extends Applet {
Image im;
public void init () {
// load
im = getImage(getDocumentBase(),"BOTTOMDOLLAR.JPG");
setBackground(Color.yellow);
}
public void paint(Graphics g ) {
g.drawImage(im, 50, 50, this); // display
}
} // end class MyApplet1
144
Applet that plays sound
import java.applet.*;
(c) Rajkumar import java.awt.*;
public class MyAppletSound extends Applet {
AudioClip ac;
public void init () {
// load
ac = getAudioClip(getDocumentBase(), "chirp1.au");
}
public void start() {
ac.loop(); // play
}
public void stop() {
ac.stop(); // stop the sound upon leaving this web page
}
} // end class MyAppletSound
145
(c) Rajkumar
Multithreading in Java
(A built-in feature in Java)
146
Single and Multithreaded
Processes
(c) Rajkumar threads are light-weight processes within a process
147
Threads
(c) Rajkumar
148
Thread states
(c) Rajkumar
new
wait()
start() sleep()
suspend()
blocked
runnable non-runnable
notify()
stop()
slept
resume()
dead unblocked
149
Threading Mechanisms...
(c) Rajkumar ❃ Create a class that extends the Thread class
❃ Create a class that implements the Runnable
interface
150
1st method: Extending Thread
class
❃
(c) Rajkumar 1st Method: Extending the Thread class
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
❃ Creating thread:
MyThread thr1 = new MyThread();
❃ Start Execution:
thr1.start();
151
An example
(c) Rajkumar
152
2nd method: Threads by implementing
Runnable interface
(c) Rajkumarclass MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
❃ Creating Object:
MyThread myObject = new MyThread();
❃ Creating Thread Object:
Thread thr1 = new Thread( myObject );
❃ Start Execution:
thr1.start();
153
An example
(c) Rajkumar
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
} // end class MyThread
class ThreadEx21 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
// due to implementing the Runnable interface
// I can call start(), and this will call run().
t.start();
} // end main()
} // end class ThreadEx2
154
A program with two threads
class ThreadEx4 {
public static void main(String [] args ) {
Thread t1 = new Thread(new MyThread());
Thread t2 = new Thread(new YourThread());
t1.start();
t2.start();
}
} // end class ThreadEx4
155
Monitor model (for
Syncronisation)
(c) Rajkumar
Method 1
Method 2
Key
Block 1
Threads
t1.start();
t2.start();
t3.start();
} // end main()
reader()
reader()
{{ writer()
writer()
-- -- -- -- -- -- -- -- -- buff[0] {{
-- buff[0]
-- -- -- -- -- -- -- -- -- --
lock(buff[i]);
lock(buff[i]); lock(buff[i]);
buff[1] lock(buff[i]);
read(src,buff[i]);
read(src,buff[i]); buff[1] write(src,buff[i]);
write(src,buff[i]);
unlock(buff[i]);
unlock(buff[i]); unlock(buff[i]);
unlock(buff[i]);
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- }}
}}
Cooperative
Cooperative Parallel
Parallel
Synchronized
Synchronized Threads
Threads
160
(c) Rajkumar
161
Streams and I/O
(c) Rajkumar
162
Display File Contents
(c) Rajkumar
import java.io.*;
public class FileToOut1 {
public static void main(String args[]) {
try {
FileInputStream infile = new FileInputStream("testfile.txt");
byte buffer[] = new byte[50];
int nBytesRead;
do {
nBytesRead = infile.read(buffer);
System.out.write(buffer, 0, nBytesRead);
} while (nBytesRead == buffer.length);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) { System.err.println("Read failed"); }
}
}
163
Filters
(c) Rajkumar
164
Writing data to a file using Filters
import java.io.*;
(c) Rajkumar public class GenerateData {
public static void main(String args[]) {
try {
FileOutputStream fos = new FileOutputStream("stuff.dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(2);
dos.writeDouble(2.7182818284590451);
dos.writeDouble(3.1415926535);
dos.close(); fos.close();
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Read or write failed");
}
}
} 165
Reading data from a file
using filters
import java.io.*;
(c) Rajkumar public class ReadData {
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("stuff.dat");
DataInputStream dis = new DataInputStream(fis);
int n = dis.readInt();
System.out.println(n);
for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble());
}
dis.close(); fis.close();
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) { System.err.println("Read or write failed");
}
}
} 166
Object serialization
(c) Rajkumar
167
Write an object to a file
import java.io.*;
(c) Rajkumar
import java.util.*;
public class WriteDate {
public WriteDate () {
Date d = new Date();
try {
FileOutputStream f = new FileOutputStream("date.ser");
ObjectOutputStream s = new ObjectOutputStream (f);
s.writeObject (d);
s.close ();
}
catch (IOException e) { e.printStackTrace(); }
Network/Socket Programming in
Java
170
java.net
(c) Rajkumar
❃ Used to manage:
❃ URL streams
❃ Client/server sockets
❃ Datagrams
171
Part III - Networking
(c) Rajkumar
ServerSocket(1234)
Output/write stream
Input/read stream
Socket(“130.63.122.1”, 1234)
Server_name: “cdacb.ernet.in” 172
Server side Socket Operations
(c) Rajkumar
174
A simple server (simplified code)
(c) Rajkumar
import java.net.*;
import java.io.*;
public class ASimpleServer {
public static void main(String args[]) {
// 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();
}
} 175
A simple client (simplified code)
177
Echo Server Client..
(c) Rajkumar
catch( UnknownHostException e )
{
System.err.println( "Don't know about host: " );
System.exit(1);
}
catch( IOException e )
{
System.err.println( "Could not get I/O for the connection to "+server);
System.exit(1);
}
}
void communicate()
{
while(true)
{
try {
System.out.print("Enter Input <end to stop>: ");
String line = kbd.readLine();
os.writeBytes( line+"\n" );
178
Echo Server Client..
if( line.equals("end") )
(c) Rajkumar { os.close(); is.close(); slink.close();
break;
}
String line2 = is.readLine();
System.out.println("Output: "+line2);
}
catch( IOException e )
{ System.out.println(e); }
}
}
public static void main( String [] args )
{
if( args.length < 2 )
{
System.out.println("Usage: java client server_name port_id" );
System.exit(1);
}
client cln = new client( args );
cln.communicate();
}
}
179
Echo Server ...
// server.java: echo server
(c) Rajkumar import java.io.*;
import java.net.*;
public class server
{
// public final static int PORT = 4779;
public static void main( String [] args )
{
ServerSocket server = null;
DataOutputStream os = null;
DataInputStream is = null;
boolean shutdown = false;
if( args.length < 1 )
{
System.out.println( "Usage: java server port_num" );
System.exit( 1 );
}
int PORT = Integer.valueOf(args[0]).intValue();
try {
server = new ServerSocket( PORT );
}
180
Echo Server ...
catch( IOException e )
(c) Rajkumar
{
System.err.println( "Could not get I/O for the connection to: ");
}
while(!shutdown)
{
if( server != null )
{
try
{
Socket client = server.accept();
System.out.println("Connected");
InetAddress cip = client.getInetAddress();
System.out.println( "Client IP Addr: "+cip.toString());
is = new DataInputStream( client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
for(;;)
{
String line = is.readLine();
if( line == null )
break;
181
Echo Server ...
(c) Rajkumar
183
Threads in Action...
Multithreaded Server
(c) Rajkumar
Server Process
Client
Process Server
Threads
Client Process
User Mode
Kernel Mode
Message Passing
Facility
184
(c) Rajkumar
Java System
Architecture &
Availability
185
A Look Inside the Java
Platform
(c) Rajkumar
Network
Java on Java on a Java on a Java on
a Browser Desktop OS Smaller OS JavaOS
186
Java Applications!
(c) Rajkumar
187
Universal Interface
(c) Rajkumar
Web Servers
with JAVA
applications
Internet
Clients
running
any OS on
any platform
188
Java on my platform ?
(c) Rajkumar
189
(c) Rajkumar
190
Sun’s Java WorkShop
(c) Rajkumar
❃ JDK:
❃ Compiler and runtime environment
❃ Class Libraries
❃ Documentation
❃ javadoc - Automated Documentation
❃ Takes comments and converts to HTML
❃ IDE: Visual Java, and integrated tools, JavaBeans
❃ Other Products and API: JavaHelp, Java Card, Java Blend,
JavaOS, Java Mail, Java Management, Java Electronic
Commerce Framework
❃ Java Enterprise API: Java Naming and Directory
Interface, Java IDL, JDBC, RMI and Object Serialization
191
Symantec Cafe 1.0
(Released)
(c) Rajkumar
192
Microsoft Jakarta
(Planned)
(c) Rajkumar
193
Borland JBuilder
(c) Rajkumar
❃ Visual RAD workbench for maximum productivity.
❃ Rapid Application Development (RAD) and Open
Component Architecture patterned after Delphi.
❃ 100+ JavaBean components, with source code, for drag-
and-drop applications.
❃ Beans Express--easiest way to create industry-standard
Java-Bean components.
❃ DataExpress -- the fastest way to build business and
database appplications.
❃ Borland DataGateway for Java connectivity to all major
database servers.
❃ Multi-tier applications with integrated RMI and CORBA.
❃ Versions: Standard, Professional, & Client/Server
194
Challenges & Possible Directions
(c) Rajkumar
✱ Performance
✱ AWT - need better GUI!
✱ Maintaining Interoperability
✱ Security - current restrictions limit what can
be done
✱ Native Compilers
✱ Is Portability that Important?
195
Comments
(c) Rajkumar
196
JDBC
(c) Rajkumar
197
Javascript and Java
(Preview)
(c) Rajkumar
198
Java for HPC!
(c) Rajkumar
❃ Many efforts are in in progress for making java as a
language for parallel programming.
❃ Java computing frameworks (HPC, numeric, data parallel)
❃ Java in distributed simulations and applications (e.g., real-
world HPC, grand chalenge)
❃ Source to source translators (C, Fortran, C++ to Java)
❃ Web based computation environment in Java
❃ Java for HPC conference:
http://www.cs.ucsb.edu/conferences/java98
❃ Java for Science and Engineering computing: subscribe java-
for-cse to majordomo@npac.syr.edu
❃ http://www.jhpc.org
199
How to Convert Programs to AWT
1.1...
(c) Rajkumar
200
How to Convert Programs to
AWT 1.1...
(c) Rajkumar
201
How to Convert Programs to
AWT 1.1
(c) Rajkumar
202
Just to Summarize
(c) Rajkumar
203
Summary
(c) Rajkumar
204
Thank
Thank You
You ...
...
(c) Rajkumar
205