You are on page 1of 23

PROJECT REPORT

(SESSION 2002-2003)
Partial fulfillment for the award of the degree of
M.Sc.
(Computer Science)

PROJECT
PROFILE
PROJECT DESCRIPTION
NAME OF COURSE M.Sc. (COMPUTER SCIENCE)
SEMESTER IV
th
(SEMESTER)
SESSION 2002-2003
NAME OF INSTITUTE GALAXY SOFTECH, JAIPUR
PROJECT ON CHAT SERVER USING JAVA
TEAM SIZE ONE
UNIVERSITY MAHARSHI DAYANAND UNIVERSITY,
ROHTAK
TEAM MEMBER NIPUN YADAV
Meaning of Project
The meaning of project is to give physical existence to the
variation brain ideas and thoughts. Project is a great source to
develop technical skills in the Technical student.
During the programming of the project student goes through
different problems and experience. A student gets a change to
climb on the roof of practical knowledge to economize to go at
the fields. A very important aim of this world PROJECT consist
of seven alphabets each of them has separate meaning.
P forPlanning Planning is good an impressive half work
is done.
R forRELAIABLE SOURCE Practice and theoretical material
and able guidance and assistance is achieved from different
sources to promote the function of planned area.
O for OVERALL EXPENSES Overall expenses to provide
final design to any project is also considerable. Their
expenses are analyzed for each concepts and method of
working on the computer.
J for JOINT EFFORTS Joint efforts are much necessary
for programming and result of any project. Many times some
problems as books etc., are solved for external sources.
E for ECONOMIC TIME FEASIBILITY It is important that
the planned scheme is how much economic time feasible. It
is must to analyze estimate for completion of the project.
C forCONSTRUCTION After analyzing the project work is
done to give logical existence of planned scheme.
T forTESTING Testing of program is done before
submitting the project after resting the gadget is ok for
use.
PREFACE
To develop a project in any language means to combine all the features of the
language, in a well planned, systematic way so as to develop and application after
an analysis of requirement, so that it will be commercially helpful. In terms of its
ultimate objectives it gives an experience of realistic application.
The aim of this project is to realistic, efficient, web based software for remote
applicant, by using programming in Java.
The project was aimed to achieve full fledge user friendliness. We have tried a lot
to achieve all the characteristics of good software. In later version it will be more
refined and integrated.
CONTENTS
Acknowledgement
Description of Team Members
System Requirement
About Programming Language
Project Description
Project Source Code
Project Output Screens
Conclusion
Bibliography
Acknowledgement
It has come out to be a sort of great pleasure and
experience for all of us to work on the project CHAT
SERVER USING JAVA.
We would like to express our appreciations to all
individuals who assisted us in any way and we sincerely of
that no one feel left out.
We also wish to express our indebtedness to those who
helped us i.e. the Director of the Institute Mr. Kapil
Dhaka during the preparation of the manual script of this
text. This would not have been made successful without his
help and precious suggestions.
We are mostly thankful to Mr. Pradosh who, guide every time
when we required with Programming and other aspect.
Finally, we also warmly thanks to all our colleagues who
encouraged us to a extent, which made the project
successful.
NIPUN YADAV
System Requirement
Hardware Requirement :
Network LAN
Processor P-I and Higher
Graphics Card
HDD- 1 GB and Higher
RAM 32 MB
Software Requirement
DOS with Windows 95 and Above
Server NT Server
Client NT Workstation
JDK 1.1.3
DEFICIENCIES OF THE CONVENTIONAL
(MANUAL) SYSTEM
1. Lack of immediate retrieval of information
In manual system, lot of time is wasted in retrieving information. Much
searching is required before required information is found. This wastes a lot
of time of the user.]
2. Lack of immediate information storage
In manual system, it is difficult to store information at proper place at that
very moment. This is because the person is unable to quickly locate the
place were the information is to be stored.
3. Promote Updation not possible
Changes are quite natural in all work of life. Information and stored data
also changes from time to time. This information up-to-date. However
bringing about changes through the manual system is a slow and tedious
process because of which inaccurate information storage occurs.
4. Very slow computation process
Lot of computational work is to be performing in the system. Activities are
quite slow in the manual system and may also be incorrect.
5. Unplanned Working
The manual system lacks the element of planned working. Records related to
customer are not properly maintained. This creates lot of problems at times
like during information retrieval and storage.
6. Insignificant generation of managerial and strategic reports
In manual system, reports for management are difficult to be generated and
strategic report almost impossible. These are because for these reports
proper storage of information. Its retrieval and its filtering are very
important and very tough in manual system.
7. Accuracy
The manual system lacks accuracy in working and a number of operations
may be performed incorrectly. The computations that are done in the
organization may be incorrect and whatever reports are generated in the
system may be inaccurate.
1. Reliability
The reliability of manual system is considered to be low because of the
above given reasons including the fact that To error in human. Any task
that is performed by man, always contain the risk of errors.

About Programming Language Java
Java was conceived by James gosling, Patric naughton, Chris warth, Ed frank, and
Mike sheriden at Sun Microsystem, inc in 1991. This language was initially called
oak but was renamed Java in 1995, between the initial implementation of oak
in the fall of 1992 and public announcement of java in the spring of 1995, many
more people contributed to the design and evolution of the language. Bill Joy,
Arthur van hoff, jonathan payne, frank yellin, and tim lindholm were key
contribution to the maturing of the original prototype.
Somewhere surprisingly, the original impetus for java was not the INTERNET !
Prototype. The primary motivation was to need for a platform-independent (that is
architecture natural) language that could be used to create software to be
embedded in various consumer electronic devices such as microwave ovens and
remote control as you can probably guess many different types of CPU are used as
controllers the trouble with C and C++ (and most other language) is that they are
designed to be compiled for a specific target. Although it is possible to compile a
C++ program for just about any type of CPU, to do so requires a full compiler
targeted for that CPU.
Java is a programming language and environment invented by James Gosling in
1994. Gosling was the first designer of the Java programming language and
implemented its original compiler and virtual machine.
Java is the first and foremost programming Language. Creation of Java was driven
by both elements in nearly equal measures which are:
1. To adapt to changing environments and uses.
2. To implement refinements and improvements in the art of programming.
"Java: A simple, object-oriented, distributed, interpreted, robust, secure, portable,
high-performance, multithreaded, and dynamic language" Java Soft
A Java Program: From Birth to Execution
1. Coding: Human-readable Java code is produced by the programmer
2. Building: A Java Development Tool "builds the Java program into byte-
code, which is saved as a ". class" file.
3. Loading: Via the web or command line, the class file is sent to the Java
Virtual Machine (VM) with an attached digital signature. The Java VM is
simply an interpreter.
4. Byte code Verification: The Java VM verifies the digital signature. When
downloaded remotely, the Java VM isolates the Java program in a restricted
part of memory. The Java program is not allowed to access local Hard drives
and System resources.
5. Internal Integrity: Verification checks are made to insure that the loaded
Java program is well formed. Data types are verified along with other syntax
structure
6. Execution: Program execution begins
Java Project
In 1990, Sun Microsystems began a project called Green to develop software for
consumer electronics. Gosling began writing software in C++ for embedding into
such items as toasters, VCR's, and Personal Digital Assistants ( PDA's ). The
embedded software makes more appliances more intelligent. Gosling's solution to
the problem of C++ was a new language called Oak. Finally in 1995, Oak was
renamed Java. Since then, Java is rising in popularity. Java Soft also sued
Microsoft, for violating its Java license agreement. Microsoft wants to add
Windows specific alterations to the Java language, which would blunt the "run
anywhere" goal of Java.
Java Soft, which presents compatibility problems with existing web browsers and
Virtual Machines are currently expanding Java. Its syntax is similar to C and C++,
but it omits many of the features that make C and C++ complex, confusing, and
unsafe. The Java platform was initially developed to address the problems of
building software for networked consumer devices. It was designed to support
multiple host architectures and to allow secure delivery of software components.
To meet these requirements, compiled code had to survive transport across
networks, operate on any client, and assure the client that it was safe to run.
The popularization of theWorld Wide Web made these attributes much more
interesting. The Internet demonstrated how media-rich content could be made
accessible in simple ways. Web browsers enabled millions of people to roam the
Net and made Web surfing part of popular culture. At last there was a medium
where what you saw and heard was essentially the same whether you were using
a Mac, PC, or UNIX machine, and whether you were connected to a high-speed
network or a slow modem.
Web enthusiasts soon discovered that the content supported by the Web's
HTML document format was too limited. HTML extensions, such as forms, only
highlighted those limitations, while making it clear that no browser could include
all the features users wanted. Extensibility was the answer.
Sun's Hot Java browser showcases the interesting properties of the Java
programming language and platform by making it possible to embed programs
inside HTML pages.
These programs are transparently downloaded into the Hot Java browser along
with the HTML pages in which they appear. Before being accepted by the browser,
the programs are carefully checked to make sure they are safe. Like HTML pages,
compiled programs are network- and host-independent. The programs behave the
same way regardless of where they come from or what kind of machine they are
being loaded into and run on.
Visitors to Web pages incorporating dynamic content can be assured that their
machines cannot be damaged by that content. Programmers can write a program
once, and it will run on any machine supplying a Java or Java 2 run time
environment.
The Java language is very secure and platform independent when compared to
alternative languages. Java's secret is the tightly integrated language model.
Java features
Simple
Java was designed to be easy for the professional programmer. It is easy to learn
and can be used effectively. If you are an experienced C++ programmer, moving to
Java will require very little effort.
Secure
There is a concept of applets in Java which can be downloaded without fear or
virus or malicious content, because the Java programs are confined to Java
execution environment and are not allowed to access other parts of the CPU.
Portable
The Java programs called Applets run in the JVM (Java virtual machine)
environment that is in every browser therefore the programs can run anywhere.
Object Oriented
Java Classes follow theOops concept of encapsulation, inheritance, and
polymorphism.
Robust
Garbage collection and Exception handling make Java a robust language. In
garbage collection the user doesnt have to bother about the memory allocation as,
when the object is no longer in use it is automatically deleted to release memory
space.
Multithreaded
A single threaded application has one thread of execution running at all times and
such programs can do only one task a time.
A multi-threaded application can have several threads of execution running
independently and simultaneously. These threads may communicate and cooperate
and will appear to be a single program to the user.
Interpreted
The Java code is compiled into the byte code, which is the class file. The byte code
is then interpreted to the machine language by the JVM environment.
Distributed
Java handles the TCP/IP protocols, which makes it easier to use in Internet.
Some Other Features Of Java Programming
Encapsulation
ENCAPSULATION is the mechanisms that binds together code and the data it
manipulates, and keeps both safe outside interference and misuse. It is a protective
wrapper that prevents the code and data from being arbitrarily accessed by other
code defined outside the wrapper.
Encapsulation is the capability to represent, denote and handle information at a
higher level that is inherent to a computer or base language. Variables and methods
are formerly known as instance variables and instance methods to distinguish from
class variables and class methods.
I nheritance
Inheritance is the process by which one object acquires the properties of another
object.
Classes inherit state and behavior from their superclass. A class is a blueprint or
prototype that defines the variables and methods common to all objects of a certain
kind.
Object oriented systems allow classes to be defined in terms of other classes. For
example, mountain bikes, racing bikes and tandems are all subclasses of the
bicycle class. Similarly, the bicycle class is the superclass of mountain bikes,
racing bikes and tandems.
Each subclass inherits state (in the form of variable declarations ) from the
superclass. Mountain bikes, racing bikes and tandems share some states : Cadence,
speed, and the like. Also each subclass inherits methods from the superclass.
Benefits of Inheritance
Subclasses provide specialized behaviors on the basis of common elements
provided by the superclass. Through the use of inheritance programmers can reuse
this code in the superclass many times.
Abstraction
Abstraction, is this process of categorising data. consider that a person is looking
for a frame in an optician's shop. To be able to choose a frame from amongst the
various types of frames available, he has to first identify the attributes he is looking
far. Once he has identified the attributes, he has with him a category or class of
frames. Similarly, to model any real life objects in OOPS an "object" has to be
instantiated from a specific "class". This basic process of forming a class is known
as "abstraction".
Java and World Wide Web
Java was basically designed for the web browsing. Java had some excellent
features which other languages did not have. The internet helped catapult java to
the forefront of programming, and java, in turn, has had a profound effect on the
internet. The reason for this quite simple:java expands the universe of objects that
can move about freely in cyberspace. Ina network, two very broad categories of
objects are transmitted between the server and your personal computer: passive
information and dynamic, active programs
For example: when you read your e-mail, you are viewing passive data. Even when
you download a program s code is still only passive data
Java/Java Applets: Java is probably the most famous of the programming
languages of the Web. Java is an object-oriented programming language similar to
C++. Developed by Sun Microsystems, the aim of Java is to create programs that
will be platform independent. The Java motto is, "Write once, run anywhere." A
perfect Java program should work equally well on a PC, Macintosh, Unix, and so
on, without any additional programming. This goal has yet to be realized. Java can
be used to write applications for both Web and non-Web use.
Web-based Java applications are usually in the form ofJava applets. These are
small Java programs called from an HTML page that can be downloaded from a
Web server and run on a Java-compatible Web browser. A few examples include
live newsfeeds, moving images with sound, calculators, charts and spreadsheets,
and interactive visual displays. Java applets can tend to load slowly, but
programming improvements should lead to a shortened loading time.
JavaScript/JScript: JavaScript is a programming language created by Netscape
Communications. Small programs written in this language are embedded within an
HTML page, or called externally from the page, to enhance the page's the
functionality. Examples of JavaScript include moving tickers, drop-down menus,
real-time calendars and clocks, and mouse-over interactions. JScript is a similar
language developed by Microsoft and works with the company's Internet Explorer
browser.
Hardware and Software Requirements for Java
Hardware Requirements
200 MHz Pentium, 160 MHz PowerPC, or 166 MHz UltraSparc
At least 64 MB RAM
486 or Pentium based PC (Pentium 100MHz or better recommended).
Display card supporting 8, 16, 24 or 32 bit display mode. (16-bit display
mode recommended for fastest video performance).
Optional: A SoundBlaster-compatible sound card for Windows machines
without built-in audio support.
Software Requirements
JDK 1.1.5 or later from Sun. (Tested on 1.1.5, 1.1.6, 1.1.7, and the Java 2
platform) Use of a JIT is strongly recommended. JDK 1.1.6 or later is required
for Y2K compatibility.
Java 2 or JDK 1.x with Swing 1.1 or above to run JMFCustomizer.
JMF classes (included in this release).
Optional: Microsoft Internet Explorer 4.01 or later.
Windows 95/98 or Windows NT 4.0.
Java Environment
Using Java, it is impossible to build applications that access libraries and
applications in other languages; that is, unless you are willing to use the underlying
operating system (OS). This is not a failure of Java, but simply a result of its lack
of external device support. Until such support is provided, Java developers must
find alternative methods to interact with libraries and applications written in other
languages. One alternative is the Java Native Interface (JNI). These techniques
provide a stop-gap measure until device support becomes part of the Java
environment
The JNI provides a documented and supported specification that allows programs
written in other languages to be called from Java. Calling Java from an application
written in another language is often referred to as embedding, and the process
requires an understanding of the Invocation API. The JNI also provides a way for
applications written in other languages to call Java.
Client/Server Model
The client places a request or order to the server. The server processes the request
of the client. The communication between the client and the server is an important
constituent in client/server model, and is usually through a network.
The client/Server model is an application development architecture designed to
separate to presentation of data form its internal processing and storage. The client
request for services and the server services these requests. The requests are
transferred from the client to the server over the network. The processing that is
done by the server is hidden from the clients.
PROTOCOLS
Java provides a rich library of network-enabled classes that allow application to
readily access network resources. There are two tools available in java for
communication. These include data grams that user data gram protocol.
(UDP) and sockets that use transmission control/internet protocol (TCP/IP).
Sockets use TCP for communication. The advantage of the socket model over
other communication models is that the server is not affected by the source of
client request. It services all requests, as long as the clients follow the TCP/IP
protocol suite. This means that the client can be any kind of computer. No longer is
the client restricted to UNIX, Windows, DOS or Macintosh platforms. Therefore,
all the computer in a network implementing TCP/IP can communicate with each
other through sockets.
SOCKETS
Socket in client/server application, the provide services like processing database
queries of modifying data in the database. The communication that occurs between
the client and the server must be reliable. The data must not be available to the
client in the same sequence in which the server sent it.
Transmission control protocol (TCP) provide a reliable, point to point
communication channel that client/Server application can used to communicate
with each other. To communicate over TCP, client and server program a
establishes a connection and bind a socket. Sockets are used to handle
communication links between an application over the network. Further
communication between the client and the server is through the socket.
Java was designed as a networking language. It makes network programming
easier by encapsulating connection functionality in the socket classes, that is, the
socket class to create a server.
IPADDRESS AND PROT
In Internet server can be through of as set of socket classes that provide additional
capabilities generally called services. Some examples of services are electronic
protocol(FTP) for transferring files across the network. Each services is associated
with a port. A port is a numeric address through with service requests, such as a
request for a web page, are processed.
Classses used by server
The procedure to create a server is to create a server socket object that listens at a
particular port for client request. When it recognize a valid request, the server
socket obtains the socket object created by the client. The communication between
the server and the client occurs using the socket.
Use the server socket class of the java. Net package to create a socket where the
server listen for remote login request. Use the IO exception class from the java.io
package to handle errors. The buffered input string class handles data transfer from
the client to the server. The print stream classes handle the transfer of data from
server to the client.
A server waits for request to come in over the network. It performs operations base
on a request and returns the result to the client. The server socket class represent
the server in a client/server application. The server socket class provides
constructor to create a socket on a specified port. A value of zero passed as an
argument for a port creates the socket on a free port.
The class provide method which :
Listen for a connection.
Return the address and local port.
Return the string representation of the socket.
The two argument constructor takes the port number, i.e. the port at which all
client requests will be serviced, and the second argument specifies the maximum
number of connection available. The tostring( ) method returns information on the
socket created. The information contains the IP address, the port address and local
port on which the socket is created. The close( ) method closes the socket. IO
Exception, which has to be caught and handled.
Listening for the client request
The run( ) method of the server, as with all threads that implement the run able
interface, has instructions for the thread. In this case, the server goes into an
infinite loop and listens for client requests. When the server secures a connection
with a client, the accept ( ) method of the server socket class accepts the
connection. The server creates an object of the user defined class connection for
the client, through the socket.
Project Description
This Project is Chat software. Through this software we can chat to one client
to another client or more another clients. For run this software we use client
server architecture in java. Java programming language is use in this project.
There are two programs in our application. One is a Server Program and
another is Client Program. When the client wants to communicate with the
server, it can do so by the graphical user interface provided. Server program
is started first which keeps listing to the clients request at a specified port.
When the client makes a request connection is established between the server
and client through the medium of socket. When the connection is made then
two or more clients can chat or talk to each other easily. Between this chat no
other client can be disturb.

HOW TO USE CHAT SERVER
Firstly we have networking for use this software because in this we
have a Serve or other is client.
Configure the Lan Card and obtain the IP Address.
Install Java Program in Client or Server Computers.
To run smoothly the java we set the path of the java programming
language
PATH=C:\JDK1.1.3\BIN
Firstly we run the Server Program and then use the Client Program
For Compile the Server Program
C:\>javac MultiChatServer.java
For run the Server Program
C:\> java MultiChatServer
For run the Client Program
C:\>javac MultiChat.java
For run the Client Program
C:\> java MultiChat <user name><IP Address>
When the server establish to connectivity to the clients then we can
chat to other client.
Before the shutdown the server we press ctrl+c to exit the server
program

import java.io.*;
import java.net.*;
import java.util.Vector;
import java.util.Enumeration;
/**
* MultiChatServer -- A chat program between any number of clients.
*
* The server acts as the central clearing house of all messages.
* To run as a server, do not supply any command line arguments.
* MultiChat will start listening on the default port, waiting
* for a connection:
*
* java MultiChatServer
*/
public class MultiChatServer {
private int port = 5001; // The default port.
private boolean listening = true;
private Vector clients = new Vector();
public static void main(String args[]) {
System.out.println("Hit control-c to exit the server.");
new MultiChatServer().server();
}

// As a server, we create a server socket bound to the specified
// port, wait for a connection, and then spawn a thread to
// read data coming in over the network via the socket.

private void server() {
ServerSocket serverSock = null;
try {
InetAddress serverAddr = InetAddress.getByName(null);

System.out.println("Waiting for first connection on " +
serverAddr.getHostName() +
" on port " + port);
// Accept up to 50 connection at a time.
// (This limit is just for the sake of performance.)
serverSock = new ServerSocket(port, 50);
} catch (IOException e) {
System.out.println(e.getMessage() +
": Failed to create server socket.");
return;
}
while (listening) {
try {
Socket socket = serverSock.accept();
System.out.println("Accepted connection from " +
socket.getInetAddress().getHostName());
DataOutputStream remoteOut =
new DataOutputStream(socket.getOutputStream());
clients.addElement(remoteOut);
new ServerHelper(socket, remoteOut, this).start();

} catch (IOException e) {
System.out.println(e.getMessage() +
": Failed to connect to client.");
}
}
if (serverSock != null) {
try {
serverSock.close();
} catch (IOException x) {
}
}
}
synchronized Vector getClients() {
return clients;
}
synchronized void removeFromClients(DataOutputStream remoteOut) {
clients.removeElement(remoteOut);
}

}
/*
* ServerHelper handles one client. The server creates one new
* ServerHelper thread for each client that connects to it.
*/
class ServerHelper extends Thread {
private Socket sock;
private DataOutputStream remoteOut;
private MultiChatServer server;
private boolean listening = true;
private DataInputStream remoteIn;
ServerHelper(Socket sock, DataOutputStream remoteOut,
MultiChatServer server) throws IOException
{
this.sock = sock;
this.remoteOut = remoteOut;
this.server = server;
remoteIn = new DataInputStream(sock.getInputStream());
}
public synchronized void run() {
String s;
try {
while (listening) {
s = remoteIn.readUTF();
broadcast(s);
}
} catch (IOException e) {
System.out.println(e.getMessage() +
": Connection to peer lost.");
} finally {
try {
cleanUp();
} catch (IOException x) {
}
}
}
// Send the message to all the sockets connected to the server.
private void broadcast(String s) {
Vector clients = server.getClients();
DataOutputStream dataOut = null;
for (Enumeration e = clients.elements(); e.hasMoreElements(); ) {
dataOut = (DataOutputStream)(e.nextElement());
if (!dataOut.equals(remoteOut)) {
try {
dataOut.writeUTF(s);
} catch (IOException x) {
System.out.println(x.getMessage() +
": Failed to broadcast to client.");
server.removeFromClients(dataOut);
}
}
}
}
private void cleanUp() throws IOException {
if (remoteOut != null) {
server.removeFromClients(remoteOut);
remoteOut.close();
remoteOut = null;
}
if (remoteIn != null) {
remoteIn.close();
remoteIn = null;
}
if (sock != null) {
sock.close();
sock = null;
}
}
protected void finalize() throws Throwable {
try {
cleanUp();
} catch (IOException x) {
}
super.finalize();
}
}

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
/**
* MultiChat -- A chat program between any number of clients.
*
* To run as a client, supply two parameters:
* 1. The name of the person to identify this user
* 2. the name the server:
* java MultiChat Spielberg bluehorse.com
* or
* java MultiChat Spielberg local // to run locally
*/
public class MultiChat extends Panel {
TextArea receivedText;
Socket sock; // The communication socket.
private GridBagConstraints c;
private GridBagLayout gridBag;
private Frame frame;
private Label label;
private int port = 5001; // The default port.
private TextField sendText;
private String hostname;
private String username;
private DataOutputStream remoteOut;
public static void main(String args[]) {
if (args.length != 2) {
System.out.println("format is: java MultiChat <username> <hostname>");
return;
}

Frame f = new Frame(args[0]);
MultiChat chat = new MultiChat(f, args[0], args[1]);
f.add("Center", chat);
f.setSize(350, 200);
f.show();
// Make the connection happen.
chat.client();
}
public MultiChat(Frame f, String user, String host) {
frame = f;
frame.addWindowListener(new WindowExitHandler());
username = user;
hostname = host;
// Build the user interface.
Insets insets = new Insets(10, 20, 5, 10); // bot, lf, rt, top
gridBag = new GridBagLayout();
setLayout(gridBag);
c = new GridBagConstraints();
c.insets = insets;
c.gridy = 0;
c.gridx = 0;
label = new Label("Text to send:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
sendText = new TextField(20);
sendText.addActionListener(new TextActionHandler());
gridBag.setConstraints(sendText, c);
add(sendText);
c.gridy = 1;
c.gridx = 0;
label = new Label("Text received:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
receivedText = new TextArea(3, 20);
gridBag.setConstraints(receivedText, c);
add(receivedText);

}
// As a client, we create a socket bound to the specified port,
// connect to the specified host, and then spawn a thread to
// read data coming coming in over the network via the socket.
private void client() {
try {
if (hostname.equals("local"))
hostname = null;
InetAddress serverAddr = InetAddress.getByName(hostname);
sock = new Socket(serverAddr.getHostName(), port);
remoteOut = new DataOutputStream(sock.getOutputStream());
System.out.println("Connected to server " +
serverAddr.getHostName() +
" on port " + sock.getPort());
new MultiChatReceive(this).start();
} catch (IOException e) {
System.out.println(e.getMessage() +
": Failed to connect to server.");
}
}
protected void finalize() throws Throwable {
try {
if (remoteOut != null)
remoteOut.close();
if (sock != null)
sock.close();
} catch (IOException x) {
}
super.finalize();
}
class WindowExitHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
// Send data out to the socket we're communicating with when
// the user hits enter in the text field.
class TextActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
// Send it.
remoteOut.writeUTF(sendText.getText());
// Clear it.
sendText.setText("");
} catch (IOException x) {
System.out.println(x.getMessage() +
": Connection to peer lost.");
}
}
}
}
/*
* MultiChatReceive takes data sent on a socket and displays it in
* a text area. This receives it from the network.
*/
class MultiChatReceive extends Thread {
private MultiChat chat;
MultiChatReceive(MultiChat chat) {
this.chat = chat;
}
public synchronized void run() {
String s;
DataInputStream remoteIn = null;
try {
remoteIn = new DataInputStream(chat.sock.getInputStream());
while (true) {
s = remoteIn.readUTF();
chat.receivedText.setText(s);
}
} catch (IOException e) {
System.out.println(e.getMessage() +
": Connection to peer lost.");
} finally {
try {
if (remoteIn != null)
remoteIn.close();
} catch (IOException x) {
}
}
}
}
PROJECT OUPTUT SCREEN
1. Server Output
C:\>java MultiChatServer
Hit control-c to exit the server.
Waiting for first connection on localhost on port 5001
2. Client Output


CONCULSION
Java is considered to be the most reliable tool for
developing client/server application. Efficient
exploration and implementing of such functionalities of
java has lead to practical challenging research
activities and development of new standards, thereby
shrinking the communication gap.
Java defined the client/sever architecture and the
powerful tool for network.
Bibliography
The Complete Reference of Java 2
- H. Schlidt
Java Programming
- Balagurusamy
Advance Java Programming
- Peter Norton

You might also like