Vous êtes sur la page 1sur 132

Multi Threading

Topics to be Covered:
1.Multi-Threaded Programming
2.Interrupting Thread
3.Thread States
4.Thread Properties
5.Thread Synchronization
6.Thread-Safe Collections
7.Executors
8.Synchronizers
9.Threads and Event-Driven Programming

INTRODUCTION
1. Multithreading extends the idea of multitasking into applications, so you can
subdivide specific operations within a single application into individual
threads. Each of the threads can run in parallel.
2. Those who are familiar with the modern operation systems such as windows 95
may recognize that they can execute several programs simultaneously. This
ability is known as multitasking. In Systems terminology, it is called
multithreading.
3. Multithreading is a conceptual programming paradigm where a program is
divided into two or more subprograms, which can be implemented at the
same time in parallel.
4. In most of our computers, we have only a single processor and therefore, in
reality, the processor is doing only one thing at a time. However, the
processor switches between the processes so fast that it appears to human
beings that all of them are being done simultaneously.
5. Java programs contain only a single sequential flow of control. This is what
happens when we execute a normal program. The program begins, runs
through a sequence of executions, and finally ends. At any given point of
time, there is only one statement under execution.
6. A thread is similar to a program that has a single flow of control. It has a
beginning, a body and an end, and executes commands sequentially. In fact, all
main programs in our earlier examples can be called single threaded
programs.

SINGLE THREADED PROGRAM

class ABC
{
--------------------------------------------------------------------------------------------------------------}

Beginning

Single
threaded body
of execution
End

MULTITHREADED PROGRAM
Main Thread
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
star
t
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread A

switchin
g

star
t
_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread B

Main method
module

star
t

switchin
g

_______________
_______________
_______________
_______________
_______________
_______________
_______________
_______________
Thread C

7. A program that contains multiple flows of control is known as


multithreaded program.
8. The above fig. is a java program with four threads, one main and three
others. The main thread is actually the main method module, which is
designed to create and start the other three threads, namely A, B and C
9. Once initiated by the main thread, the threads A, B and C run
concurrently and share the resources jointly. The ability of a language to
support multithreads is referred to as concurrency.
10. Threads in java are subprograms of main application program and share
the same memory space, they are known as lightweight threads or
lightweight processes..
Note:
It is important to remember that threads running in
parallel does not really mean that they actually run at the same
time. Since all the threads are running on a single processor, the
flow of execution is shared between the threads.

CREATING THREADS
1. Creating threads in Java is simple.
2. Threads are implemented in the form of objects that contain a
method
called run().
3. The run() method is the heart and soul of any thread. It makes
up the
entire body of a thread and is the only method in which the
threads
behavior can be implemented.
4. A typical
run()
would
appear as follows:
public
void
run()
{
----------------------------------Statements for implementing
-----------------thread
}

5. The run() method should be invoked by an object for the concerned


thread.
6. This can be achieved by creating the thread and initiating it with the
help of
another thread method called start().
7. A new thread can be created in two ways.
a. By extending a thread class:
Define a class that extends Thread class and override
its run() method
with the code required by the thread.
b. By converting a class to a thread:
Define a class that implements Runnable interface. The
Runnable
interface has only one method, run(), that
is to be defined in the
method with the code to be executed by the thread.

1. EXTENDING THE THREAD CLASS


We can make our class runnable as a thread by extending the class
java.lang.Thread. This gives us access to all the thread methods directly.
It includes the following steps:
1. Declare the class as extending the Thread class
executing the

2. Implement the run() method that is responsible for


sequence of code that the thread will execute.

initiate the

3. Create a thread object and call the start() method to


thread execution.

1. Declaring the
class
class MyThread extends Thread
{
--------------------------------------------------------}

2. Implementing the run()


Method
public void run()
{
----------------------------------------------------------------}

Thread Code Here

3. Starting New
Thread
MyThread aThread = new MyThread();
aThread.start();

//Invoke run() method

Creating threads using the thread


class A extendsclass
Thread
{

public void run()


{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");
}
}

class C extends Thread


{
public void run()
{
for(int k = 1;k <= 5;k++)
{
System.out.println("\tFrom Thread C : k = " + k);
}
System.out.println("Exit from C ");
}
}
class ThreadExtend
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
a.start();
b.start();
c.start();
}
}

Output:
From Thread A : i = 1
From Thread C : k =
From Thread B : j =
From Thread C : k =
From Thread A : i =
From Thread C : k =
From Thread B : j =
From Thread C : k =
From Thread A : i =
From Thread C : k =
From Thread B : j =
Exit from C
From Thread A : i =
From Thread B : j =
From Thread A : i =
From Thread B : j =
Exit from A
Exit from B

2. IMPLEMENTING THE RUNNABLE INTERFACE


The Runnable interface declares the run() method that is required for
implementing threads in our programs. To do this, we must perform the steps
listed below:
1. Declare the class an implementing the Runnable interface.
2. Implementing the run() method.
3. Create a thread by defining an object that is instantiated from
the
runnable class as the target of the thread.
4. Call the threads start() method to run the thread.
1. Creating Class:
class MyThread implements Runnable
{
--------------------------------------------------------}

2. Implementing the run()


Method
public void run()
{
----------------------------------------------------------------}

Thread Code Here

3. Starting New Thread and assign the


runnable object
MyThread runnableObj = new MyThread();
Thread t = new Thread(runnableObj);
t.start();

//Invoke run() method

import java.lang.Thread;
class X implements Runnable
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class Y implements Runnable
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");
}
}

class Z implements Runnable


{
public void run()
{
for(int k = 1;k <= 5;k++)
{
System.out.println("\tFrom Thread C : k = " + k);
}
System.out.println("Exit from C ");
}
}
class RunnableTest
{
public static void main(String args[])
{
X runnableX = new X();
Thread threadX = new Thread(runnableX);
Y runnableY = new Y();
Thread threadY = new Thread(runnableY);
Z runnableZ = new Z();
Thread threadZ = new Thread(runnableZ);
threadX.start();
threadY.start();
threadZ.start();
}
}

Interrupting Thread:
Using sleep() method:
Make the thread to sleep for a while. In that particular sleep time the
processor executes the other Threads which is ready for an execution.
It should thrown a exception called java.lang.InterruptedException, so it
must be handled in the program using try-catch.
Syntax:
Thread.sleep(millisec);
class A implements Runnable
{
public void run()
{
try{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " +
i);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println("Thread 1 Interrupted");
}
System.out.println("Exit from A ");

class B extends Thread{


public void run()
{
try{
for(int j = 1;j <= 5;j++) {
System.out.println("\tFrom Thread B : j = " +
j);
Thread.sleep(2000);
}
}
catch(InterruptedException e) {
System.out.println("Thread 2 Interrupted");
}
System.out.println("Exit from B ");
}
}
class ThreadSleep{
public static void main(String args[])
{
A a = new A();
B b = new B();
Thread t1 = new Thread(a);
t1.start();
b.start();
}

Thread Class and Runnable Interface:


To create a new thread, your program will either extend Thread class or
implements the Runnable interface.
The Thread class defines several methods that help manage threads.
Methods

Meaning

getName()

Obtain a threads name

getPriority()

Obtain a threads priority

isAlive()

Determine if a thread is still


running

join()

Wait for a thread to terminate

run()

Entry point for the thread

sleep()

Suspend a thread for a period of


time

start()

Start a thread by calling its run


method

currentThread(
)

Return the Currently executing


thread

LIFE CYCLE OF A
THREAD
During the life time of a thread, there are many states it can enter.
They include
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

State Transition diagram of a Thread


New
Thread

Newborn
start

stop

Active Thread

Runnable

Running

stop

Dead

yield

suspen
d

resum
e

sleep

notify

wait
Idle Thread
(Not
Runnable)

Killed
Thread

Blocked

stop

import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
if(i == 1) yield();
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
if(j==3) stop();
}
System.out.println("Exit from B ");
}
}

class C extends Thread


{
public void run()
{
for(int k = 1;k <= 5;k++)
{
System.out.println("\tFrom Thread C : k = " + k);
if(k==1)
try
{
sleep(1000);
}
catch(Exception e)
{
}
}
System.out.println("Exit from C ");
}
}
Output:
class ThreadTest_1
Start Thread A
{
Start Thread B
public static void main(String args[])
From Thread A : i = 1
{
From Thread B : j = 1
A a = new A();
From Thread B : j = 2
B b = new B();
Start Thread C
C c = new C();
System.out.println("Start Thread A");
a.start();
System.out.println("Start Thread B");
b.start();
System.out.println("Start Thread C");
c.start();
System.out.println("End of main Thread");
}
}

From Thread B
From Thread A
From Thread C
End of main Thread
From Thread A
From Thread A
From Thread A
Exit from A
From Thread C
From Thread C
From Thread C
From Thread C
Exit from C

:j=3
:i=2
:k=1
:i=3
:i=4
:i=5
:
:
:
:

k
k
k
k

=
=
=
=

2
3
4
5

Using isAlive() and join()


isAlive()
Two ways exist to determine whether a thread has finished or not. First,
you can call isAlive() on the thread. The method is defined by Thread, and its
general form is shown here:
final boolean isAlive()
The isAlive() method returns true if the thread upon which it is called is still
running. It returns false otherwise.

join()
While isAlive() is occasionally useful, the method that you will more
commonly use to wait for a thread to finish is called join(), shown here:
final void join() throws InterruptedException
This method waits until the thread on which it is called terminates. Its
name comes from the concept of the calling thread waiting until the
specified thread joins it.

class A extends Thread


{
public void run()
{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i = " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");
}
}

class C extends Thread


{
public void run()
{
for(int k = 1;k <= 5;k++)
{
System.out.println("\tFrom Thread C : k = " +
k);
}
System.out.println("Exit from C ");
}
}
class AliveJoin
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();

System.out.println("Start Thread A");


a.start();
System.out.println("Start Thread B");
b.start();
System.out.println("Start Thread C");
c.start();
System.out.println("End of main Thread");
System.out.println("Thread One is Alive: " +
a.isAlive());
System.out.println("Thread two is Alive: " +
b.isAlive());
System.out.println("Thread three is Alive: " +
c.isAlive());
try
{
a.join();

b.join(); c.join();

}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Thread One is Alive: " +

THREAD PRIORITY
1. In java, each thread is assigned a priority, which affects the order in which it is
scheduled for running.
2. The threads of the same priority are given equal treatment by the Java scheduler
and, therefore, they share the processor of a first come, first serve basis.

ThreadName.setPriority(int Number);
The intNumber is an integer value to which the threads priority is set.
The Thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value
between 1 and 10. Note that the default setting is NORM_PRIORITY.

import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i = 1;i <= 5;i++)
{
System.out.println("\tFrom Thread A : i
= " + i);
}
System.out.println("Exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j = 1;j <= 5;j++)
{
System.out.println("\tFrom Thread B : j = " + j);
}
System.out.println("Exit from B ");

class C extends Thread


{
public void run()
{
for(int k = 1;k <= 5;k++)
{
System.out.println("\tFrom Thread C : k = " + k);
}
System.out.println("Exit from C ");
}
}
class ThreadPriority
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
c.setPriority(5); //c.setPriority(NORM_PRIORITY);
b.setPriority(10); //b.setPriority(MAX_PRIORITY);
a.setPriority(1); //a.setPriority(MIN_PRIORITY);
a.start();
System.out.println("Priority of A class Thread: "+ a.getPriority());
b.start();
System.out.println("Priority of B class Thread: "+ b.getPriority());
c.start();
System.out.println("Priority of C class Thread: "+ c.getPriority());
}
}

yield() method:
Thread gives up CPU for other threads ready to run
class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
this.name = name;
}
public void run()
{
for (int i=0;i<10;i++) {
System.out.println(name + ": hello world");
yield();
}
}
}
public class Main3
{
public static void main(String [] args)
{
MyThread t1 = new MyThread("thread1");
MyThread t2 = new MyThread("thread2");
t1.start(); t2.start();
}
}

Race Condition:
Two or more threads need to share access to the same data.
If two threads have access to the same object and each calls to a method
that modifies the state of the object, then the threads depend on the order
in which the data were accessed, corrupted objects can result. Such a
condition is often called Race Condition.
class MyThread extends Thread
{
private String name;
public MyThread(String name)
{
this.name = name;
}
public void run()
{
for (;;)
System.out.println(name + ": hello world");
}
}
public class RaceCondition
{
public static void main(String [] args) {
MyThread t1 = new MyThread("thread1");
MyThread t2 = new MyThread("thread2");
t1.start(); t2.start();
}
}

Synchronization in Threads:

When we start two or more threads within a program, there may be a


situation when multiple threads try to access the same resource and
finally they can produce unforeseen result due to concurrency issue.
For example if multiple threads try to write within a same file then they
may corrupt the data because one of the threads can overwrite data or
while one thread is opening the same file at the same time another thread
might be closing the same file.
So there is a need to synchronize the action of multiple threads and
make sure that only one thread can access the resource at a given point
in time.
This is implemented using a concept calledmonitors (also called as
Semaphore).
Each object in Java is associated with a monitor, which a thread can lock
or unlock.
Only one thread at a time may hold a lock on a monitor.
To enter an objects monitor, just call a method that has been modified
with the synchronized keyword.
The monitor is used to control the way in which synchronized methods are
allowed to access the class or object.
When a synchronized method is invoked for a given object, it is said
toacquirethe monitor for that object. No other synchronized method may
be invoked for that object until the monitor is released.
A monitor is automatically released when the method completes its
execution and returns. A monitor may also be released when a synchronized

While creating Synchronized methods within classes that you create is an


easy and effective means of achieving synchronization, it will not work in
all cases.
Syntax:
access_specifier
synchronized
method_name(parameters)
{
---------// function body
}
class MyThread extends Thread
{
static String message[] ={
"Engineering",
"Technology."};
String id;
public MyThread(String id)
{
this.id = id;
}
public void run()
{

"Chettinad",

void

"College",

"of",
"and",

class SynchronizedOutput
{
public static synchronized void displayList(String name,String
list[])
{
try {
for(int i=0;i<list.length;++i)
{
System.out.println(name+list[i]);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Interruption occured");
}
}
}
class ThreadSynchronization
{
public static void main(String args[])
{
try{
MyThread thread1 = new MyThread("Thread1:

thread1.start();
if (thread1.isAlive())
{
thread1.join();
System.out.println("Thread1 is dead.");
}
thread2.start();
if (thread2.isAlive())
{
thread2.join();
System.out.println("Thread 2 is dead.");
}
}
catch(InterruptedException e)
{
}
}
}

Output:
Thread1: Chettinad
Thread1: College
Thread1: of
Thread1: Engineering
Thread1: and
Thread1: Technology.
Thread1 is dead.
Thread2: Chettinad
Thread2: College
Thread2: of
Thread2: Engineering
Thread2: and
Thread2: Technology.
Thread 2 is dead.

APPLETS
38

What is Applets?
1. An applet is a program written in the Java programming language that can be included in an
HTML page, much in the same way an image is included in a page.
2. When you use a Java technology-enabled browser to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual
Machine (JVM).

What are the differences between Applets and Application?


1. Applets do not use the main() method for initiating the execution of the code. Applets, when
loaded, automatically call certain methods of Applet class to start and execute the applet
code.
2. Unlike stand alone applications, applets cannot be run independently. They are run from
inside a Web page using a special feature known as HTML tag.
3. Applets cannot read from or write to the files in the local computer.
4. Applets cannot communicate with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++. (Java
39
language supports this feature through native methods.)

Applet Architecture
1. An applet is a window based program.
2. First, applets are event driven.
3. Event driven architecture impacts the design of an applet.
4. An applet resembles a set of interrupt service routines.
5. An applet waits until an event occurs.
6. The AWT notifies the applet about an event by calling an event handler appropriate action
and then quickly return control to the AWT.
7. Second, the user initiates interaction with an applet - not the other way around.
8. As you know, in a non - windowed program, when the program needs input, it will prompt
the user and then call some input method, such as readLine().
9. This not the way it works in an applet. Instead, the user interacts with the applet as he or she
wants, when must respond.
10. For example, when the user clicks a mouse inside the applets window, a mouse clicked
event is generated. If the user presses a key while the applets window has input focus, a
keypress event is generated.
11. Applets can contain various controls, such as push buttons and check boxes.

40

Applet Architecture . . . .
12. When the user interacts with one of these controls, an event is generated.
13. While the architecture of an applet is not as easy to understand as that of a console based
program, Javas AWT makes it as simple as possible.
14. If you have written programs for windows, you know how intimidating that environment can
be.
15. Fortunately, Javas AWT provides a much cleaner approach that is more quickly mastered.

41

An Applet Skeleton or Applet Life Cycle

Begin

Born

(Load Applet)

Initialization

start( )

stop( )

Running

Stopped

Idle

start( )

Display

paint( )

destroy( )

Destroyed

Dead

End

42
Exit of Browser

An Applet Skeleton or Applet Life Cycle


1. All but the the most trivial applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the applet and controls its
execution.
2. Four of these methods init( ), start( ), stop( ), and destroy( ) are defined by Applet.
Another, paint(), is defined by the AWT Component class.
3. Default implementations for all of these methods are provided.
4. Applets do no need to override those methods they do not use.
5. However, only very simple applets will not need to define all of them.
The applet states is:
1. Born or initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
5. Display state
43

1. Initialization State
Applet enters the initialisation state when it is first loaded. This is achieved by calling the
init() method of Applet Class. The applet is born. At this stage, we may do the following, if
required,
a. Create objects needed by the applet.
b. Set up initial values
c. Load images or fonts
d. set up colors
public void init( )
{
----------------------------------------------------------------}

Action

44

2. Running State
Applets enters the running state when the system call the start () method of Applet Class.
This occurs automatically after the applet is initailized. Starting can also occur if the applet is
already in stopped state. For example, we may leave the web page containing the applet
temporarily to another page and return back to the page. This again starts the applet running.
Note that, unlike init() method, the start() method may be called more than once. We may
override the start() method to create a threa to control the applet.

public void start( )


{
----------------------------------------------------------------}

Action

45

3. Idle or Stopped State


An applet becomes idle when it is stopped from running. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the
stop() method explicitly. If we use a thread to run the applet, then we must use stop() method
to terminate the thread. We can achieve by overriding the stop( ) method:

public void stop( )


{
----------------------------------------------------------------}

Action

46

4. Dead State
An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy( ) method when we quit the browser. Like initialization, destroying
stage occurs only once in the applets life cycle. If the applet has created any resources. Like
threads we may override the destroy( ) method to clean up these resouces.

public void destroy( )


{
----------------------------------------------------------------}

Action

47

5. Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint()
method is called to accomplish this task. Almost every applet will have a paint() method.
Like other methods in the life cycle, the default version of paint() method does absolutely
nothing. We must therefore override this method if we want anything to be displayed on the
screen.
public void paint (Graphics g)
{
--------------------------------Display Statements
--------------------------------}

48

import java.awt.*;
import java.applet.*;
/*
<applet code = "AppletDemo" width = 300 height =
300>
</applet>
*/
public class AppletDemo extends Applet
{
String msg;
public void init()
{
setBackground(Color.cyan);
}
public void start()
{
msg += "This is Start method";
}
public void stop()
{
msg += "This is Stop method";
}
public void destroy()
{
msg += "This is Destroy method";
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}

Specified Colors

Specified Colors

1. Color.black

10. Color.pink

2. Color.blue

11. Color.red

3. Color.cyan

12. Color.white

4. Color.darkGray

13. Color.yellow

5. Color.gray
6. Color.green
7. Color.lightGray
8. Color.magenta
9. Color.orange

49

How the applets to be displayed in the Browser

<HTML>
<HEAD>
<TITLE>WELCOME TO cHETTINAD</TITLE>
</HEAD>
<BODY>
<APPLET
CODE = AppletDemo.class
WIDTH = 300
HEIGHT = 200
</APPLET>
</BODY>
</HTML>

50

The HTML APPLET Tag


< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
.......
[HTML Displayed in the absence of Java]
</APPLET>

51

ATTRIBUTE

MEANING

CODE = AppletFileName.class

Specifies the name of the applet class to be loaded. That is, the name of the
already compiled .class file in which the executable. Java bytecode for the
applet is stored. This attribute must be specified.

CODEBASE = codebase_URL
(Optional)

Specifies the URL of the directory in which the applet resides. If the applet
resides in the same directory as the HTML file, then the CODEBASE
attirbute may be omitted entirely.

WIDTH = pixels
HEIGHT = pixels

These attributes specify the width and height of the space on the HTML
page that will be reserved for the applet.

NAME=applet_instance_name
(Optional)

A name for the applet may optionally be specified so that other applets on
the page may refer to this applet. This facilitates inter applet
communication.

ALIGN = alignment
(Optional)

This optional attribute specifies where on the page the applet will appear.
Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT,
MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE.

HSPACE = pixels
(Optional)

Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies
the amount of horizontal blank space the browser should leave surrounding
the applet.

VSPACE = pixels
(Optional)

Used only when some vertical alignment is specified with the ALIGN
attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical
blank space the browser should leave surrounding the applet.

ALT = alternate_text
(Optional)

Non java browser will display this text where the applet would normally
go. This attribute is optional.

PARAM NAME AND VALUE

The PARAM tag allows you to specify applet specific arguments in an


52
HTML page. Applets access their attributes with the getParameter()
method

Passing Parameters to Applets


import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width = 300 height = 300>
<param name = fontName value=Courier>
<param name = fontSize value = 30>
<param name = leading value=2>
<param name = accountEnabled value = true>
</applet>
*/
public class ParamDemo extends Applet
{
String fontName;
int fontSize;
float leading;
boolean active;
public void start()
{
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";

53

param = getParameter("fontSize");
try
{
if(param != null) //if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
param = getParameter("leading");
try
{
if(param != null) //if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e)
{
leading = -1;
}

54

param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName,0,10);
g.drawString("Font Size: " + fontSize,0,20);
g.drawString("Leading: " + leading, 0,42);
g.drawString("Account Active: " + active,0,58);
}
}

55

getCodeBase() and getDocumentBase()


import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code=ParamDemo_2.class width = 300 height = 300>
</applet>
*/
public class ParamDemo_2 extends Applet
{
public void paint(Graphics g)
{
String msg;
URL url = getCodeBase();
msg = "Code Base: " + url.toString();
g.drawString(msg,10,20);
url = getDocumentBase();
msg = "Document Base: " + url.toString();
g.drawString(msg,10,40);
}
}

56

The AudioClip Interface


The AudioClip interface defines these methods:
1. play ( )

play a clip from the beginning.

2. stop ( )

stop playing the clip.

3. loop ( )

play the loop continuously.

4. getAudioClip ( ) - After you have loaded an audio clip


import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*
<applet code=SoundExample width = 300 height = 300>
</applet>
*/
public class SoundExample extends Applet implements MouseListener
{
AudioClip soundFile1;
AudioClip soundFile2;

57

public void init()


{
soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav");
soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav");

addMouseListener(this);
setBackground(Color.yellow);
soundFile1.play();
}
public void paint(Graphics g)
{
g.drawString("Click to hear a sound",20,20);
}
public void mouseClicked(MouseEvent evt)
{
soundFile2.play();
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
58

AppletStub Interface
The AppletStub interface provides a way to get information from the run-time browser
environment. The Applet class provides methods with similar names that call these
methods. Methods
public abstract boolean isActive ()
The isActive() method returns the current state of the applet. While an applet is
initializing, it is not active, and calls to isActive() return false. The system marks the
applet active just prior to calling start(); after this point, calls to isActive() return true.
public abstract URL getDocumentBase ()
The getDocumentBase() method returns the complete URL of the HTML file that loaded
the applet. This method can be used with the getImage() or getAudioClip() methods to
load an image or audio file relative to the HTML file.
public abstract URL getCodeBase ()
The getCodeBase() method returns the complete URL of the .class file that contains the
59
applet. This method can be used with the getImage() method or the getAudioClip()

public abstract String getParameter (String name)


The getParameter() method allows you to get parameters from <PARAM> tags within the
<APPLET> tag of the HTML file that loaded the applet. The name parameter of
getParameter() must match the name string of the <PARAM> tag; name is case insensitive.
The return value of getParameter() is the value associated with name; it is always a String
regardless of the type of data in the tag. If name is not found within the <PARAM> tags of
the <APPLET>, getParameter() returns null.
public abstract void appletResize (int width, int height)
The appletResize() method is called by the resize method of the Applet class. The method
changes the size of the applet space to width x height. The browser must support changing
the applet space; if it doesn't, the size remains unchanged.

60

The Delegation Event Model


1. The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events.
2. Its concept is quite simple: a source generates an event and sends it to one or more listeners.
3. In this scheme, the listener simply waits until it receives an event.
4. Once received, the listener processes the event and then returns.
5. The advantage of this design is that the application logic that processes events is cleanly separated
from the user interface logic that generates those events.
6. A user interface element is able to delegate the processing of an event to a separate piece of code.

Events
1. In the delegation model, an event is an object that describes a state change in a source.
2. It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
3. Some of the activities that cause events to be generated are pressing a button, entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.
4. Event may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software or
61
hardware failure occurs, or an operation is completed.

Event Sources
1. A source is an object that generates an event.
2. This occurs when the internal state of that object changes in some way.
3. Sources may generate more than one type of event.
4. A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
5. Each type of event has its own registration method.
6. Here is the general form:

public void addTypeListener(TypeListener el)


7. Here, type is the name of the event and el is a reference to the event listener.
8. For example the method that registers a keyboard event listener is called addKeyListener().
9. The method that registers a mouse motion listener is called addMouseListener().
10. When an event occurs, all registered listeners are notified and receive a copy of the event object.
11. This known as multicasting the event. Some sources may allow only one listener to register.
12. The general form of such method is this:
62
public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException

13. Here, Type is the name of the event and el is a reference to the event listener.
14.When such an event occurs, the registered listener is notified. This is known a s unicasting the
event.
15. A source must also provide a method that allows a listener to unregister an interest in a specific
type of event.
16. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
17. Here, Type is the name of the event and el is reference to the event listener.
18. For Example, to remove a keyboard listener, you would call removeKeyListener().
19. The methods that add or remove listeners are privided by the source that generates events.
20. For example, the Component class provides methods to add and remove keyboard and mouse event
listeners.

Event Listeners
21. A Listener is an object that is notified when an event occurs. It has major requirements.
22. First, it must have been registered with one or more sources to receive notification about specific
type of events.
23. Second, it must implement methods to receive and process these notifications.

63

24. The methods that receive and pricess events are defined in a set of interfaces found in
java.awt.event.
25. For example, the MouseMotionListener interface defines two method to receive notifications when
the mouse is dragged or moved.
26. Any object may receive and process one or both of these events if it provides an implementation of
this interface.

64

EVENT CLASSES

65

Event Classes
1. The classes that represent events are at the core of Javas event handling
mechanism.
2. At the root of the Java event class hierarchy is EventObject, which is in java.util.
3. It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
4. Here, src is the object that generates this event.
5. EventObject contains two methods: getSource() and toString().
6. The getSource() method returns the source of the event.
7. Its general form is shown here:
Object getSource()
8. As expected, toString() returns the string equivalent of the event.
9. The AWTEvent, defined within the java.awt package, is a subclass of EventObject.
10. It is the superclass of all AWT based events used by the delegation event model.
11. Its getID() method can be used to determine the type of the event. The signature of
this method is shown here:

int getID()

66

The package java.awt.event defines several types of events that are generated by
various user interface elements.
EVENT CLASSES

DESCRIPTION

ActionEvent

Generated when a button is pressed, a list item is double - clicked, or a menu


item is selected.

AdjustmentEvent

Generated when a scroll bar is manupulated

ComponentEvent

Generated when a component is hidden, moved, resized, or becomes visible.

ContainerEvent

Generated when a component is added to or removed from a container.

FocusEvent

Generated when a component gains or loses keyboard focus.

InputEvent

Abstract super class for all component input event classes.

ItemEvent

Generated when a check box or list item is clicked; also occurs when a choice
selection is made or a checkable menu item is selected or deselecte.

KeyEvent

Generated when input is received from the keyboard.

MouseEvent

Generated when the mouse is dragged, moved, clicked, pressed, or , released;


also generated when the mouse enters or exits a component.

MouseWheelEvent

Generated when the mouse wheel is moved.

TextEvent

Generated when the value of a text area or text field is changed.

WindowsEvent

Generated when a window is activated, closed, deactivated, deiconified,


67
iconified, opened, or quit.

The ActionEvent Class


1. An ActionEvent is generated when a button is pressed, a list item is double - clicked, or a menu
item is selected.
2. The ActionEvent class defines fout integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and
SHIFT_MASK.
3. In addition. There is an integer constant, ACTION_PERFORMED, which can be used to identify
action events. ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)

4. Here, src is a reference to the object that generated this event.


5. The type of the event is specified by type, and its command string is cmd.
6. The argument modifiers indicates which modifier key were pressed when the event was generated.
7. The when parameter specifies when the event occurred.
68

Action Event Example Button Click


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Button_Setnull.class" height=300 width=300>
</applet>
*/
public class Button_Setnull extends Applet implements ActionListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Button b1;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
//setTitle("Addition of Two Numbers");
setLayout(null);
69

l1 = new Label("Enter the A Value");


l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Addition of the Two Numbers");
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
b1 = new Button("Click Addition");
b1.setBounds(100,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(b1);
b1.addActionListener(this);

70

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand().equals("Click Addition"))
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
}
}

71

Action Event Example List Box item Double Click


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=Listbox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Listbox_Setnull extends Applet implements ActionListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
List ls;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
72
l3.setBounds(0,100,170,25);

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ls = new List();
ch.setBounds(100,150,150,25);
ls.add(""); ls.add("Addition"); ls.add("Subtraction");
ls.add("Multiplication"); ls.add("Division"); ls.add("Clear");
ls.add("Total No. of Item"); ls.add("Get Selected Item");
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ls);
ls.addActionListener(this);
}

73

public void actionPerformed(ActionEvent ae)


{
if(ls.getSelectedIndex() == 1)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 2)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}

74

if(ls.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ls.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ls.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
75
}
}

You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand() method, shown here:
String getActionCommand()
For example, when a button is pressed, and action event is generated that has a command name equal
to the label on that button.
The getModifiers() method returns a value that indicates which modifier keys(ALT,CTRL,META and
SHIFT) were pressed when the event was generated. Its form is shown here:
String getModifiers()

The AdjustmentEvent Class


An AdjustementEvent is generated by a scroll bar. There are five types of adjustment events. The
AdjustementEvent class defines integer constants that can be used to identify them.
BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT The user Clicked inside the scroll bar to increase its value.
TRACK The slider was dragged.
UNIT_DECREMENT The button at the end of the scroll bar was clicked to decrease its value
UNIT_INCREMENT The button at the end of the scroll bar was clicked to increase its value.
76

In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED,


that indicates that a change has occurred.
Here is one AdjustmentEvent constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)
Here, src is a reference to the object that generated this event. The id equals
ADJUSTEMENT_VALUE_CHANGED. The type of the event is specified by type, and its
associated data is data.
The getAdjustable() method returns the object that generated the event. Its
form is shown here:
Adjustable getAdjustable()
The type of the adjustement event may be obtained by the getAdjustmentType() method.
It returns one of the constant defined by AdjustmentEvent. The general form is shown
here:
int getAdjustmentType()
The amount of the adjustement can be obtained from the getValue() method, shown
here
int getValue()
77

import java.applet.*; AdjustmentEvent Example Horizontal and Vertical Scrollbar Changed


import java.awt.*;
import java.awt.event.*;
/*
<applet code="Scroll_Setnull.class" height=300 width=1000>
</applet>
*/
public class Scroll_Setnull extends Applet implements AdjustmentListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Scrollbar sbh,sbv;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
78
l3.setBounds(0,100,170,25);

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
int height = Integer.parseInt(getParameter("height"));
int width = Integer.parseInt(getParameter("width"));
sbh = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,height);
sbh.setBounds(0,275,975,25);
sbv = new Scrollbar(Scrollbar.VERTICAL,0,1,0,width);
sbv.setBounds(975,0,25,300);
sbh.setUnitIncrement(50);
sbh.setBlockIncrement(50);
sbv.setUnitIncrement(20);
sbv.setBlockIncrement(20);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(sbh);
add(sbv);
sbh.addAdjustmentListener(this);
sbv.addAdjustmentListener(this);
}

79

public void adjustmentValueChanged(AdjustmentEvent ae)


{
if(sbh.getValue() == 50)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 100)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}

80

if(sbh.getValue() == 150)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 200)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 250)
{
tf1.setText("");
}
}
}

tf2.setText("");

tf3.setText("");
81

The ComponentEvent Class


A ComponentEvent is generated when the size, position, or visibility of a component is
changed. There are four types of component events. The ComponentEvent class defines
integer constants that can be used to identify them. The constant and their meanings are
shown here:
COMPONENT_HIDDEN
The component was hidden
COMPONENT_MOVED

The component was moved

COMPONENT_RESIZED

The component was resized

COMPONENT_SHOWN

The component became visible

ComponentEvent has this constructor


ComponentEvent(Component src, int type)
Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
ComponentEvent is the superclass either directly or indirectly
ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent.

of

The getComponent() method returns the component that generated the event.
It is shown here:
82
Component getComponent()

The ContainerEvent Class


1. A ContainerEvent is generated when a component is added to or removed from a
container.
2. There are two types of container events.
3. The ContainerEvent class defines int constants that can be used to identify them:
COMPONENT_ADDED and COMPONENET_REMOVED.
4. They indicate that a component has been added or removed form the container.
5. ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)
Here, src is reference to the container that generated this event. The type of the event is
specified by type, and the component that has been added to or removed from the
container is comp.
You can obtain a reference to the container that generated this event by using
the getCotnainer() method, shown here:
Container getContainer()
The getChild() method returns a reference to the component that was added to
or removed from the container. Its general form is shown here:
83
Component getChild()

The FocusEvent Class

A FocusEvent is generated when a component gains or loses input focus. These events are
identified by the integer constants FOCUS_GAINED and FOCUS_LOST
FocusEvent is a subclass of ComponentEvent and has threse constructor:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
1. Here, src is a reference to the component that generated this event.
2. The type of the event is specified by type.
3. The argument temporaryFlag is set to true if the focus event is temporary.
4. Otherwise, it is set to false.
5. The other component involved in the focus change, called the apposite component, is passed in
other.
6. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost
focus.
7. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains
focus.
84

import java.applet.*;
FocusEvent Example Focus Gained and Focus Lost in TextBox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Focus_Event.class" height=300 width=1000>
</applet>
*/
public class Focus_Event extends Applet implements FocusListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
add(tf1);
add(tf2);

add(tf3);

tf1.addFocusListener(this);

tf2.addFocusListener(this);

85

public void focusGained(FocusEvent fe)


{
tf2.setText("Focus Gained");
}
public void focusLost(FocusEvent fe)
{
tf1.setText("Focus Lost");
}
}

86

You can determine the other component by calling getOppositeComponent(),


shown here.
Component getOppositeComponent()
The isTemporary() method indicates if this focus change is temporary. Its form
is shown here:
boolean isTemprorary()
The method returns true if the change is temporary. Otherwise, it returns false.

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
MOUSE_CLICKED

The user clicked the mouse.

MOUSE_DRAGGED

The user dragged the mouse.

MOUSE_ENTERED

The mouse entered a component.

MOUSE_EXITED

The mouse exited from a component.

MOUSE_MOVED

The mouse moved.

MOUSE_PRESSED

The mouse was pressed.

MOUSE_RELEASED

The mouse was released.

MOUSE_WHEEL

The mouse wheel was moved.

87

MouseEvent is a subclass of InputEvent. Here is one of its constructor.


MouseEvent(Component src, int type, long when, int modifiers, int x,int y, int clicks, boolean triggersPopup

1. Here, src is a reference to the component that generated the event.


2. The type of the event is specified by type.
3. The system time at which the mouse event occurred is passed in when.
4. The modifiers aregument indicates which modifiers were pressed when a mouse
event occurred.
5. The coordinates of the mouse are passed in x and y.
6. The click count is passed in clicks.
7. The triggersPopup flag indicates if this event causes a pop up menu to appear on
this platform
Methods

Description

int getX() and int getY()

These retrun the X and Y coordinates of the mouse when the event
occured

Point getPoint()

It returns a Point object that contains the X, Y coordinates in its integer


members.

getClickCount()

The methods obtains the number of mouse clicks for this event

isPopupTrigger()

This method tests if this event causes a pop up menu to appear on 88


this
platform

import java.awt.*;
MouseEvent Example
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}

in Mouse

89

public void mousePressed(MouseEvent m)


{
X=10;
Y=20;
msg="CCET";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}

90

public void mouseDragged(MouseEvent m)


{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

91

The MouseWheelEvent Class


The MouseWheelEvent class encapsulates a mouse wheel event. If a mouse has a
wheel, it is located between the left and right buttons. Mouse wheels, are used for
scrolling. MouseWheelEvent defines these two integer constants.
WHEEL_BLOCK_SCROLL
WHEEL_UNIT_SCROLL

A page up or page down scroll event occurred


-

A line up or line down scroll event occured

MouseWheelEvent defines the following constructor:


MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks,
boolean triggersPopup, int scrollHow, int amount, int count)
Here, src is a reference to the object that generated the event. The type of the event is
specified by type. The system time at which the mouse event occurred is passed in
when. The modifiers argument indicates which modifiers were pressed when the event
occurred. The coordinates of the mouse are passed in x and y. The number of clicks the
wheel has rotated is passed in clicks. The triggers Popup flag indicates if this event
causes a pop up menu to appear on this platform. The scrollHow value must be either
is passes in amount. The count parameter indicates the number of roational units that
the wheel moved.
92

Methods

Description

int getWheelRotation()

It returns the number of rotational units. If the value is positive, the wheel
moved conterclockwise. If the value is negative, the wheel moved
clockwise.

int getScrollType()

It returns either WHEEL_UNIT_SCORLL or WHEEL_BLOCK_SCROLL

int getScrollAmount()

If the scroll type is WHEEL_UNIT_SCROLL you can obtain the number of


units to scroll by calling getScrollAmount().

The InputEvent Class


1. The abstract class InputEvent is a subclass of ComponentEvent and is the
superclass for component input events.
2. Its subclasses are keyEvent and MouseEvent.InputEvent defines several integer
constants that represent any modifiers, such as the control key being pressed, that
might be assocated with the event.
3. Originally, the InputEvent class defined the following eight values to represent the
modifiers.
ALT_MASK

BUTTON2_MASK

BUTTON3_MASK

SHIFT_MASK

BUTTON1_MASK

CTRL_MASK

META_MASK

93

4. However, because of possible conflicts between the modifiers used by keyboard


events and mouse events, and other issues, Java2 version 1.4, added the following
extended modifier values.
ALT_DOWN_MASK

BUTTON2_DOWN_MASK

BUTTON3_DOWN_MASK

SHIFT_DOWN_MASK

BUTTON1_DOWN_MASK

CTRL_DOWN_MASK

META_DOWN_MASK

5. When writing new code, it is recommended that you use the new, extended modifiers
rather that the original modifiers.
6. To test if a modifier was pressed at the time an event is generated, use the
isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown()
methods.
7. The forms of these methods are shown here:
boolean isAltDown()
boolean isAltGraphDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()

94

You can obtain a value that contains all of the original modifer flags by calling the
getModifiers() method. It is shown here:
int getModifiers()
You can obtain the extended modifiers by called getModifiersEx(), which is shown here:
int getModifiersEx()

The ItemEvent Class


1. An ItemEvent is generated when a check box or a list item is clicked or when a
checkable menu item is selected or deselected.
2. There are two types of item events, which are identified by the following integer
constants.
DESELECTED

- The user deselected an item

SELECTED

- The user selected an item

In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that


signifies a change of state.
ItemEvent(ItemSelectable src, int type, Object entry, int state)

95

3. Here, src is a reference to the component that generated this event.


4. For example, this might be a list or choice element.
5. The type of the event is specified by type.
6. The specific item that generated the item event is passed in entry. The current state of
that item is in state.
7. The getItem() method can be used to obtain a reference to the item that generated an
event. Its signature is shown here:
Object getItem()
8. The getItemSelectable() method can be used to obtain a reference to the
ItemSelectable object that generated an event. Its general form shown here:
itemSelectable getItemSelectable()
9. Lists and choices are examples of user interface elements that implement the
ItemSelectable interface.
10. The getStateChange() method returns the state change for the event. It is shown
here:
int getStateChange()

96

import java.applet.*;
ItemEvent Example in Checkbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkbox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkbox_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Addition of the Two Numbers");
l3.setBounds(0,100,170,25);

97

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch1 = new Checkbox("Addition");
ch1.setBounds(100,150,150,25);
ch2 = new Checkbox("Subtraction");
ch2.setBounds(250,150,150,25);
ch3 = new Checkbox("Multiplication");
ch3.setBounds(400,150,150,25);
ch4 = new Checkbox("Division");
ch4.setBounds(550,150,150,25);
ch5 = new Checkbox("Clear");
ch5.setBounds(700,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1);
add(ch2); add(ch3); add(ch4); add(ch5);
ch1.addItemListener(this); ch2.addItemListener(this);
ch3.addItemListener(this); ch4.addItemListener(this);
ch5.addItemListener(this);
}

98

public void itemStateChanged(ItemEvent ie)


{
if(ch1.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ch2.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}

99

if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}

tf2.setText("");

tf3.setText("");
100

import java.applet.*;
ItemEvent Example in CheckboxGroup
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkboxgroup_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkboxgroup_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
CheckboxGroup cbg;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
cbg = new CheckboxGroup();
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
101
l3 = new Label("Compute the Two Numbers");
l3.setBounds(0,100,170,25);

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch1 = new Checkbox("Addition",cbg,false);
ch1.setBounds(100,150,150,25);
ch2 = new Checkbox("Subtraction",cbg,false);
ch2.setBounds(250,150,150,25);
ch3 = new Checkbox("Multiplication",cbg,false);
ch3.setBounds(400,150,150,25);
ch4 = new Checkbox("Division",cbg,false);
ch4.setBounds(550,150,150,25);
ch5 = new Checkbox("Clear",cbg,false);
ch5.setBounds(700,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1);
add(ch2); add(ch3); add(ch4); add(ch5);
ch1.addItemListener(this); ch2.addItemListener(this);
ch3.addItemListener(this); ch4.addItemListener(this);
ch5.addItemListener(this);
}

102

public void itemStateChanged(ItemEvent ie)


{
if(ch1.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
l3.setVisible(true);
tf3.setVisible(true);
}
if(ch2.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}

103

if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}

tf2.setText("");

tf3.setText("");
104

ItemEvent Example in Choice Box


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Choicebox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Choicebox_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Choice ch;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
105
l3.setBounds(0,100,170,25);

tf1 = new TextField(10);


tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch = new Choice();
ch.setBounds(100,150,150,25);
ch.add(""); ch.add("Addition"); ch.add("Subtraction");
ch.add("Multiplication"); ch.add("Division"); ch.add("Clear");
ch.add("Total No. of Item"); ch.add("Get Selected Item");
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch);
ch.addItemListener(this);
}

106

public void itemStateChanged(ItemEvent ie)


{
if(ch.getSelectedIndex() == 1)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 2)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}

107

if(ch.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ch.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ch.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
108
}
}

The KeyEvent Class


1. A KeyEvent is generated when keyboard input occurs.
2. There are three types of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED and KEY_TYPED.
3. The first two events are generated when any key is pressed or released.
4. The last event occurs only when a character is generated.
5. Remember, not all key presses result in characters.
6. For example, pressing the SHIFT key does not generate a character.
7. There are many other integer constants that are defined by KeyEvent.
8. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII
equivalents of the numbers and letters. Here are some others:
VK_ENTER

VK_ESCAPE

VK_CANCEL

VK_UP

VK_DOWN

VK_LEFT

VK_RIGHT

VK_PAGE_DOWN

VK_PAGE_UP

VK_SHIFT

VK_ALT

VK_CONTROL
109

9. The VK constants specify virtual key codes and are independent of any modifiers,
such as control, shift, or alt. KeyEvent is a subclass of InputEvent.
10. Here are two of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
11. Here, src is a reference to the component that generated the event.
12. The type of the event is specified by type.
13. The system time at which the key was pressed is passed in when.
14. The modifiers argument indicates which modifiers where pressed when this key
event occurred.
15. The virutal key code, such as VK_UP, VK_A, and so forth, is passed in code.
16. The character equivalent is passed in ch. If no valid character exists, then ch
contains CHAR_UNDEFINED.
17. For KEY_TYPED events, code will contain VK_UNDEFINED.
18. The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar(), which returns the character that was entered, and getKeyCode(), which
110
returns the key code.

//the key event handles


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=Key_Event.class width=300 height=100>
</applet>
*/
public class Key_Event extends Applet implements KeyListener
{
String msg="";
int x=10,y=20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

KeyEvent Example in Keyboard

111

Their general forms are shown here:


char getKeyChar()
int getKeyCode()
If not valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When
a KEY_TYPED event occurs, getKeyCode() returns VK_UNDEFINED

The TextEvent Class


Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program. TextEvent defines the integer
constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here:
TextEvent(Object src, int type)

Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
112

import java.applet.*;
TextEvent Example in Textbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Text_Event.class" height=300 width=1000>
</applet>
*/
public class Text_Event extends Applet implements TextListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
add(tf1);
add(tf2);
add(tf3);
tf1.addTextListener(this);
tf2.addTextListener(this);
}
public void textValueChanged(TextEvent te)
{
tf3.setText(tf1.getText());
113
}
}

The WindowEvent Class


There are ten types of window events. The WindowEvent class defines integer constants
that can be used to identify them. The constant and their meanings are shown here:
WINDOW_ACTIVATED

- The window was activate

WINDOW_CLOSED

- The window has been closed

WINDOW_CLOSING

- The user requested that the window be closed

WINDOW_DEACTIVATED

- The window was deactivated.

WINDOW_DEICONIFIED

- The window was deiconified.

WINDOW_GAINED_FOCUS

- The window gained input focus.

WINDOW_ICONIFIED

- The window was iconified.

WINDOW_LOST_FOCUS

- The window lost input focus.

WINDOW_OPENED

- The window was opened.

WINDOW_STATE_CHANGED

- The state of the window changed.

114

WindowEvent is a subclass of ComponentEvent. It defines the following constructor.


WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is
type.

The most commonly used method in this class is getWindow(). It returns the Window
object that generated the event. Its general form is shown here:
Window getWindow()

115

Event Classes

Event Listener Interfaces

Event Listener Interfaces Methods

ActionEvent

ActionListener

void actionPerformed(ActionEvent ae)

AdjustmentEvent

AdjustmentListener

void adjustmentValueChanged(AdjustmentEvent ae)

ComponentEvent

ComponentListener

void componentResized(ComponentEvent ce)


void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(CommonentEvent ce)

ContainerEvent

ContainerListener

void componentAdded(ContainerEvent ce)


void componentRemoved(ContainterEvent ce)

FocusEvent

FocusListener

void focusGained(FocusEvent fe)


void focusLost(FocusEvent fe)

ItemEvent

ItemListener

void itemStateChanged(ItemEvent ie)

KeyEvent

KeyListener

Void keyPressed(KeyEvent ke)


Void keyReleased(KeyEvent ke)
Void KeyTyped(KeyEvent ke)

MouseEvent

MouseListener

void mouseClicked(MouseEvent me)


void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

MouseMotionListener

void mouseDragged(MouseEvent me)


void mouseMoved(MouseEvent me)

InputEvent

116

Event Classes

Event Listener Interfaces

Event Listener Interfaces Methods

MouseWheelEvent

MouseWheelListener

void mouseWheelMoved(MouseWheelEvent mwe)

TextEvent

TextListener

void textChanged(TextEvent te)

WindowEvent

WindowsListener

void windowActivated(WindowEvent we)


void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

WindowFocusListener

Void windowGainedFocus(WindowEvent we)


Void windowLostFocus(WindowEvent we)

117

Sources of Events
Event Source

Description

Button

Generates action events when the button is pressed.

Checkbox

Generates item event s when the check box is selected or deselected.

Choice

Generates item event s when the choice is changed.

List

Generates action event s when an item is double clicked; generates item


event when an item is selected or deselected.

Menu Item

Generates action event swhen a menu item is selected; generates item


events when a checkable menu item is selected or deselected.

Scrollbar

Generates adjustment event when the scroll bar is manipulated.

Text components

Generates text events when the user enters a character.

Window

Generated window events when a window is activated, closed, deactivated,


deiconified, iconified, opened, or quit.

118

APPLET CONTROLS

119

120

Networking

Computer on Internet communicate to each other using any one of the


following:
Transmission Control Protocol(TCP)
User Datagram Protocol(UDP)
Every Host in the network is identified by using unique ID - Internet protocol
(IP) addresses
Every host on Internet has a unique IP address
143.89.40.46, 203.184.197.198 203.184.197.196, 203.184.197.197,
127.0.0.
More convenient to refer to using hostname string
cse.ust.hk, tom.com, localhost
One hostname can correspond to multiple internet addresses:
www.yahoo.com:
66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84;
Domain Naming Service (DNS) maps names to numbers

121

Networking

Socket

A socket is bound to a port number so that the TCP layer can identify the
correct application for data

Ports
Many different services can be running on the host. A port identifies a service
within a host
Many standard port numbers are pre-assigned time of day 13, ftp 21, telnet 23,
smtp 25, http 80
IP address + port number = "phone number for service
protocols : rules that facilitate communications between machines
Examples:
1.HTTP: HyperText Transfer Protocol
2.FTP: File Transfer Protocol
3.SMTP: Simple Message Transfer Protocol
4.TCP: Transmission Control Protocol
5.UDP: User Datagram Protocol, good for, e.g., video delivery)
122
Protocols are standardized and documented. So machines can reliably work
with one another

Networking

Client-Server interaction
Communication between hosts is two-way, but usually the two hosts take
different roles
Server
Server waits for client to make request
Server registered on a known port with the host ("public phone number")
Usually running in endless loop
Listens for incoming client connections
Server offers shared resource (information,database, files, printer, compute
power) to clients

Client
Client "calls" server to start a conversation
Client making calls uses hostname/IP address and port number
Sends request and waits for response
Standard services always running ftp, http, smtp, etc. server running on
123
host using expected port

Networking Socket level


java.net.Socket is an abstraction of a bi-directional communication
Programming
channel between hosts
Send and receive data using streams

OutputStream

InputStream

Client

Server
InputStream

OutputStream

124

Client/Server Communications
The server must be running when a client
starts. The server waits for a connection request
from a client. To establish a server, you need to
create a server socket and attach it to a port,
which is where the server listens for
connections.

Server Host
Server socket on port 8000
SeverSocket server =
new ServerSocket(8000);

Client Host

I/O Stream

A client socket
Socket socket =
server.accept()
After a server
socket is
created, the
server can use
this statement
to listen for
connections.

After the server accepts


the connection,
communication between
server and client is
conducted the same as for
I/O streams.

Client socket
Socket socket =
new Socket(host, 8000)

125

The client issues


this statement
to request a
connection to a
server.

Networking Communication
TCP
- Transmission Control Protocol
Protocols

Reliable - When TCP segments, the smallest unit of TCP transmissions, are
lost or corrupted, the TCP implementation will detect this and retransmit
necessary segments
Connection-oriented - TCP sets up a connection before transmission of any
data
Continuous Stream - TCP provides a communication medium that allows for
an arbitrary number of bytes to be sent and received smoothly

UDP User Datagram Protocol


Unreliable - UDP has no mechanism for detecting errors nor for
retransmission of lost data
Connectionless - UDP does not negotiate a connection before transmission
of data
Message-oriented - UDP allows application to send self-contained messages
within UDP datagrams

126

Networking

Occasionally, you would like to know who is connecting to the server. You
can use the InetAddress class to find the client's host name and IP
address. The InetAddress class models an IP address. You can use the
statement shown below to create an instance of InetAddress for the client
on a socket.
InetAddress inetAddress = socket.getInetAddress();
Next, you can display the client's host name and IP address, as follows:
System.out.println("Client's host name is " +
inetAddress.getHostName());
System.out.println("Client's IP Address is " +
inetAddress.getHostAddress());

127

Networking - Inside Java.net

The
Socket
Server Socket
DatagramSocket and
MulticastSocket

Classes implement client and server sockets for connection-oriented and


connectionless communication.

128

UDP Client

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

class UDPClient
{
publicstaticvoid main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(24);
byte buff[]=newbyte[1024];
DatagramPacket dpack=new DatagramPacket(buff,buff.length);
dsoc.receive(dpack);
System.out.println(new String(dpack.getData()));
}
}

129

UDP Server

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

class UDPServer
{
publicstaticvoid main(String args[]) throws Exception
{
DatagramSocket dsoc=new DatagramSocket(5217);
InetAddress host=InetAddress.getLocalHost();
String str=(new Date()).toString();
byte buf[]=str.getBytes();
dsoc.send(new DatagramPacket(buf,buf.length,host,24));
dsoc.close();
}
}
130

TCP - Simple-Client Example


This client tries to connect to a server (coming soon) and port given on
the command line, then sends some output to the server, and finally
receives some input which is printed on the screen.

TCP
- Simple-Server Example
The server creates a server socket that listen on the port given on the command
line. It then enters infinite loop doing the following: when a connection with a client
is established it reads some input from the client (terminated with a 0 byte), sends
back the message Simon says: plus the input received, and closes the connection.