Вы находитесь на странице: 1из 55

Project Report

Chat Server

CONTENTS
INTRODUCTION
ANALYSIS
TOOLS OVERVIEW
o NETWORKING
o GUI
o DATABASE
DFD
IMPLEMENTATION
o DESIGN FORM
o CODE
o USER MANUAL
SYSTEM SPECIFICATION
APPLICATION & LIMITATION
REFERENCES

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

1. Introduction
Client server computing is a phrase used to describe a model for
computer networking. This model offers an efficient way to provide
information and services to many users. A network connection only made
when information need to be accessed by user. This lack of continuous
network connection provides network efficiency.
In client server computing, processes are divided between the client
and server. This relationship based on series of request and responses.

Client: - Request services or information from another computer (the server


computer).
Server: - Response to the clients request by sending the results of the
request back to the

client computer.

In a client/server setting, the client computer runs a software


application called client program. This software allows a computer to act as
client.
The client Program: - Enables the users send a request for the information
to the server. Format the request so that the server can understand it. Format
the response from the server in a way that the user can read.

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

In a client/server setting, the server computer runs a software


application called server program. This software allows a computer to act as
server.
The server Program: - Receives a request from a client and processes the
request. Responds by sending the requested information back to the client.
The following diagram illustrates the relationship between the client and
server computer.

Request

Response

Send a request

Process a request

Read Result

send back result

Figure 2.1. Client Server Computing

The client request information, the server processes the request


and sends a response back to the client. Most transaction that occurs on the
Internet is client/server based. Some examples include: -

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

FTP (File Transfer protocol): - An FTP client program contacts an FTP


server and request the transfer of a file. The server responds by transferring
the file to the client.
WWW (World Wide Web): - In this case the client program is browser. A
browser requests the contents of a web page and displays the results on the
users computer.

E-Mail: - A mail client program enables the user to interact with a server in
order to access, read and send an electronic mail messages.
In Summary: - Client/server computing is a common networking
model, which enables many users to access information in an efficient
manner. Generally, the user computer is called client and the machine that
contains the information being accessed is called server. The client program
runs an application called client program. A client program enables the user
send request fir information to the server and read the results that server send
back. The server computer runs a server program, which processes the
requests and sends the results back to the client. Most Internet transaction,
such as FTP, E-Mail and accessing web pages are based on client/server
networking.

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

2. ANALYSIS
In this project we are going to design an application of socket
programming through which number of clients can communicate with each
other with the help of server. This is the main objective of this project.
For this project we are going to use java as front-end and SQL
database as backend tool. To implement this project we use Windows 2000
as software.
The requirement specification of this project is Windows 98,Windows
NT, and Windows 2000, javas JDK1.3 version, SQL as database to store
users IDs and passwords and floppy drive and CD-drive.
It is a global chat application for Windows sockets. It allows two
clients to carry on a conversation using a server as the intermediary. Chat
applications allow inexpensive and efficient social interactions between
communities members spread across the globe. A community can use the
Chat application to allow its members to have an interactive session with a
special guest or a community member through the means of a moderated

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

chat. A customer support site can use the Chat application to offer instant
responses to its customers regarding its products.
For e.g. if any person have urgent information which is in one place
and hence wants to talks with another person for that purpose chat server is
useful. Because of this the time is spend less.

3. TOOL OVERVIEW
3.1 NETWORKING:
Client-Server Definition:
Client/server is a computational architecture that involves the client
processes

requesting services

from server

processes.

Client/server

computing is a logical extension of modular programming. Modular


programming has its fundamental assumption that separation of a large piece
of software into its constituent parts (modules) creates the possibility for
development and better maintainability. Client/server computing takes this a
step farther by recognizing that those modules that need not all be executed
within the same memory space.
With this architecture, the calling module becomes the client(that
which requests a services), and called module becomes the server(that
which provides the service). The logical extension of this is to have clients
and servers running on the appropriate hardware and software platforms for
their functions. For example, Database Management System servers running
on platforms specially designed and configured to perform queries, or file
Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

servers running on platforms with special elements for managing files. It is


this latter perspective that has created the widely believed myth that
client/server has something to do with PCs or UNIX machines.

A Client Process: The client is a process (program) that sends a message to a server
process (program), requesting that server perform a task (services), Client
program usually manage the user-interface portion of the application,
validate data entered by the user, dispatch request to the server programs,
and sometimes executes business logic. The client-based process is the frontend application that user sees and interacts with. The client process contains
solution specific logic and provides the interface between the user and the
rest of the application system. The client process also manages the local
resources that the users interact with such as the monitor, keyboard,
workstation CPU and peripherals. One of the key elements of a client
workstation is the Graphical User Interface (GUI). Normally a part of
operating system i.e. the windows manager detects user actions, manages the
windows on the displays the data in a windows.
A Server Process: A server process (program) fulfills the client request by performing
the task requested. Server programs generally receive request from a client
program, execute database retrieval and updates, and manage data integrity
and dispatch responses to the client requests. Sometimes server programs
execute common or complex business logic. The server-based process may
run on another machine on the network. This server could be host operating
system or network file server; the server is then provided both the file
Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

system services and application services. Or in some cases, another desktop


machine provides the application services. The server process act as
software engine that manages shared resources such as databases, printers,
communication links, or high-power processors. The server process
performs the back-end tasks that are common to the similar application.
Middleware: Connectivity allows application to transparently communicate with
other program or processes, regardless of their location. The key element of
connectivity is the network operating system (NOS). NOS provide services
such as routing, distribution, messaging, file and print, and network
management services. NOS rely on a communication protocols to provide
services. The protocol is divided in three groups: media, transport and
client/server protocols.
Media protocol determines the type of physical connections used on a
network (some example of media Protocol are Ethernet, Token Rings, fiber
distributed data interface (FDDI), coaxial and twisted pair). A transport
protocol the mechanism to move pockets of data from client to the server
(some example of transport protocol are Novells IPX/SPX, Apples Apple
Talk, Transmission Control protocol/Internet Protocol (TCP/IP) Open
System

Interconnection

(OSI)

and

Government

Open

System

Interconnection Profile (GOSIP)). Once the Physical has been established


and transport protocol chosen, a client/server protocol is required before the
user can access the network services. A client /server protocol dictates the
manner in which clients request information and services from a server and
also how the server replies to that request.

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

Client-Server System:

Client

Client

Client

Network

Client

Server

Figure 3.2.1 General structure of a Client-Server System.

Front-End

SQL user
interface

Forms
interface

Report
Writer

Graphical
interface

Interface
SQL engine

Institute of Petrochemical Engineering, Lonere

Project Report

Chat Server

Back End

Figure 3.2.2 front-end and back-end functionality.

Institute of Petrochemical Engineering, Lonere

10

Project Report

Chat Server

Networking of computers allows some tasks to be executed on server


system, and some tasks to be executed on the client system. The figure 3.2.1
shows that many clients are connected to the only one server. This figure
also shows the general structure of the Client-Server System.
The functionality of the Client-Server system is broadly divided
between two parts: The front end and the back end-as in figure 3.2.2. The
back end manages access structure, query evaluation and optimization,
concurrency control, and recovery. The front end of the database system
consists of a tool such as forms, report writers and graphical user interface
facilities. The interface between front end and back end is through SQL, or
through application program.
In earlier generation database system, the lack of such standard
necessities that the front end and the back end provided by the same
software vendors. With the growth of the interface standard, different
vendors often provide the front end user interface and the back end server.
Application development tools are used to construct user interface; they are
graphically tool that can be used to construct interfaces without any
programming, some of the popular application tools are Power Builder,
magic, and Borland Delphi; Visual basic is also used for the application
development
Further, certain application programs, spreadsheet and staticallyanalysis packages, use the client server interface directly to access data from
back end server. In effect, they provide front end specialized for particular
tasks.
Some transition processing systems are providing a transactional
remote procedure call interface to connect client with server. This call
appear like ordinary procedure calls to the programmer, but all the procedure
Institute of Petrochemical Engineering, Lonere

11

Project Report

Chat Server

calls from the client are enclosed in a single transaction at the server end.
Thus, if the transaction aborts, the server can undo the effect of the
individual remote procedure calls

Socket Connection:
A socket is an abstraction through which an application may send and
receive data, in much the same way as an open file allows an application to
read and write data to stable storage. A socket is a software endpoint of
communication.
For e.g.: an electrical circuit board has to have a socket to enable it to
send current to a TV. Similarly the TV has a socket. The connection plug is
fixed at one end into the TV socket and at the other end into the circuit board
socket.
Information written to the socket by an application on one machine
can be read by application on a different machine and vice versa.
This application layer on one computer has to create a socket in order
to connect to the application layer on another computer sockets at both ends
seems to be connected horizontally between application layers. But, actually,
the socket is bound to a software port. It is the duty of the lower layers to
route data to the appropriate port.

Establishing a Simple Server (using Stream Sockets):


Establishing a Simple Server in java requires five steps.
Step1:

To create a ServerSocket object. A call to the ServerSocket

constructor is

Institute of Petrochemical Engineering, Lonere

12

Project Report

Chat Server

SERVERSOCKET S = NEW SERVERSOCKET (port, queueLength);


Register an available port number and specifies a maximum
number of the client that can request connection to the server. (i.e.
queueLength). If the queue is the full, client connection are
automatically refused. The preceding statement establishes the port
where the waits for connections from clients (also known as the
binding the server to the port). Each client will ask to the server on
this port.
Each client connection is managed with a Sockets object. Once the
ServerSockets is established.
Step 2:

The server listens indefinitely (or blocks) for an attempt by

client to connect. This is accomplished with a call to the ServerSocket


accept method as in
Socket connection = s.accept ();
Which returns a Socket object when a connection is established.
Step 3:

To get the OutputStream and InputStream object that enable the

server to connect with a client. The server sends information to the


client via an OutputStream object. The server receives the information
from the client via Inputstream object. To obtain the stream, the server
invokes the method getOutput stream on the Socket to get reference to
the OutputStream associated with the Sockets and invokes the method
getInputStream on the Socket to get a reference to the InputStream
associated with a socket.
The OutputStream and InputStream object can be used to send
and receive individual byte or set of bytes with the OutputStream
method writer and the InputStream method read, respectively. Often it
Institute of Petrochemical Engineering, Lonere

13

Project Report

Chat Server

is useful to send or receive value of primitive data types (such as int


and double) or class data types (such as String and employee) rather
than

sending

bytes

(such

as

ObjectOutputStream

and

ObjectInputStream) to the OutputStream and InputStream associate


with the socket. For example
ObjectInputStream input = new ObjectInputStream connection.
GetInputStream ());
ObjectOutputStream output = new ObjectOutputStream
connection.getOutputStream ());
The beauty of establishing these relationships is that whatever
the server writes to the ObjectOutputStream is sent via the
OutputStream and is available to clients InputStream and whatever
the clients writes to its OutputStream (with a corresponding
ObjectOutputStream) is available via the servers InputStream.
Step 4:

The processing phase in which the server and the client

communicate via the InputStream and OutputStream objects.


Step 5:

When the transmission is complete, the server closes the

connection by invoking the close method on the Socket.

Establishing a Simple Client (using Stream Sockets):


Establishing a Simple client in java requires four steps.
Step1:

We can create a Socket to connect the server. The connection


the connection to the server is established using calls to the socket

Institute of Petrochemical Engineering, Lonere

14

Project Report

Chat Server

constructor with two arguments-the server Internet address and the


port number-as in
Socket connection = new Socket (serverAddress, port);
If the connection attempt is successful, this returns the Socket.
A connection attempt that fails throws an instance of the subclass of
IOException. So many programs simply catch IOException.
Step 2:

Socket methods getInputStream and getOutputStream are used

to get the reference to the Sockets associates InputStream and


OutputStream, respectively. InputStream method read can be used to
input individual bytes or sets of bytes to the server. Often it is useful
to send and receive value of primitive data types (such as int and
double) or class data types (such as String or Employee) rather than
sending bytes. If the server is sending information in the form of
actual data types, the client should receive the information in the same
format. Thus, if the server sends values with an ObjectOutputStream,
the client should read those values with an ObjectOutputStream.
Step 3:

The processing phase in which the client and the server

communicate via
inputStream and OutputStream objects.
Step 4:

When the transmission is complete, the client closes the

connection by invoking close method on the Socket. When the


processing information is send by the server, the client must determine
when the server is done sending information so client can call close to
close the Socket connection.
Institute of Petrochemical Engineering, Lonere

15

Project Report

Chat Server

When the client closes the socket. An IOException may throw.


The getInputStream and getOutputStream methods may also throw
IOExceptions. Java provides stream sockets. With stream sockets a
process established a connection to another process. While the
connection is in place, data flows between processes in continuous
stream. Stream sockets are said to provide a connection-oriented
service. The protocol used for transmission is the popular TCP
(Transmission Control Protocol). When using an ObjectOutputStream
and ObjectInputStream to send and receive object over a network
connection, always create ObjectOutputStream first and flush the
stream so the ObjectInputStream can prepare to receive the data.
Client/Server interacts with Stream Socket Connections.
Socket Functions:
Socket(): Creates a TCP or UDP socket, which may then be used as an end
point of communication for sending and receiving data using the specified
protocol. Specify TCP and UDP with socket type/protocol pair from stream
or datagram protocol.
Bind(): Assign the local Internet address and port for a socket. The port
number must be specified. The call will fail if the specified port number is
the local port of some other socket.
Getsockname(): Returns the local information for a socket in a sockaddr
structure.

Institute of Petrochemical Engineering, Lonere

16

Project Report

Chat Server

Connect(): Establishes a connection between the given the socket and the
remote socket associated with the foreign address, if any. Upon returning
successfully, the given sockets local and remote IP address and port
information are filled in. if the socket was not previously bound to a local
port, one is assigned randomly. For TCP sockets, connect() returns
successfully only after completing a handshake with the remote TCP
implementation; success implies the existence of a reliable channel to that
socket.
Listen(): Indicate the given socket is ready to accept incoming connection.
The socket must already be associated with the local port. After this call,
incoming TCP connection request addressed to the given local port will be
completed and queued until they are passed to the program via accept().
Accept(): Blocks waiting for connections addressed to the IP address and
port to which the given socket is bound. When a connection arrives and the
TCP handshake is successfully completed, a new socket have been filled in
with the local port number of the new socket, and the addressed information
has been returned in the sockaddr structure.
Send(): Sends the bytes contained in the buffer over the given socket. The
socket must be in a connected state. When the call returns, the data has been
queued for transmission over the connection. For a stream socket, the data
will eventually be transmitted, provided the connection closes normally. For
a datagram socket there are no guarantees of delivery. However, the data
from a single send() call will never be split across multiple recv() calls. The
return value indicates the number of bytes actually transmitted. The flags
Institute of Petrochemical Engineering, Lonere

17

Project Report

Chat Server

argument allows various special protocol features, such as out of band data,
to be accessed.
Sendto(): Sends the bytes contained in the buffer over the given the socket.
To use sendto() on a TCP socket requires a socket to be in the connected
state.
Recv(): Copies up to a specified number of bytes, received on the socket,
into a specified location. The given socket must be in the connected state.
Normally, the call blocks until either at least one byte is returned or the
connection closes. The return value indicates the number of bytes actually
copied into the buffer starting at the pointed to location. For a stream socket,
the bytes are delivered in the same order as they were transmitted, without
omission. For a datagram socket, each recv() returns the data from at most
one send() and order is not necessarily preserved. If the buffer provided to
recv() is not big enough for the next available datagram, the datagram is
silently truncated to the size of the buffer.
Recvfrom(): Copies up to a specified number of bytes, received on the
socket, into a specified location. To use recvfrom() on a TCP socket requires
the socket to be in the connected state.
Close(): Terminates communication on a socket. The socket is marked to
disallow further sends and receives.
Shutdown(): Terminates communication on a socket. The socket is marked
to disallow further sends and receives, or both, according to the second
Institute of Petrochemical Engineering, Lonere

18

Project Report

Chat Server

parameter: if it is 0,further receives will be disallowed. If it is 1, further


sends are disallowed. If it is 2,both sends and receives will be disallowed.
The socket must be in the connected state.

Exception Handling:
Exception handling should be used to process only exceptional
situations where a method to complete its task for reasons it cannot control.
To process exceptions from program components that are not geared to
handling those exceptions directly. To process exceptions from software
components such as methods, libraries and classes that are likely to be used
and where those components cannot handle their own exceptions. On large
projects to handle exceptions in a uniform manner project wide. Exception is
an indication that a problem occurred during the programs execution. Using
java exception handling enables the programmer to remove the error
handling code from the main line of the programs execution. This improves
program clarity and enhances modifiability.
Java exception handling enables a program to catch all types of
exceptions, or to catch all exceptions of a certain type, or to catch all
exceptions of related types. Exception handling is provided to enable
programs to catch and handle errors rather than letting them occur and
suffering the consequences. Exception handling is designed for error
processing, which is an infrequent activity that is often used because a
program is about to terminate.
Exception handling helps improve a programs fault tolerance. It
becomes more pleasant to write error-processing code, so programmers
are more likely to provide it. Exception handling is particularly well suited
Institute of Petrochemical Engineering, Lonere

19

Project Report

Chat Server

to systems of separately developed components. Such systems are typical of


real-world software systems and products. Exception handling makes it
easier to combine the components and have them work together effectively.
Throwing an exception:
The throw statement is executed to indicate that an exception has
occurred. This is called throwing an exception. A throw statement specifies
an object to be thrown. The operand of a throw can be of any class
throwable. The two immediate subclasses of class throwable are exception
and error. Errors are particularly serious system problems that generally
should not be caught. Exceptions are caused by problems most java
programmers will want to deal with. If the operand is an object of class
exception, it is called an exception object.
When an exception is thrown, control exits the current try block and
proceeds to an appropriate catch handler after that try block. It is possible
that the throw point could be in a deeply nested scope within a try block;
control will still proceed to the catch handler. It is also possible that the
throw point could be in a deeply nested method call, still, control will
proceed to the catch handler.
A try block may appear to contain no error checking and include no
throw statements, but code referenced in the try block could certainly cause
error-checking code in constructors to execute and possibly throw
exceptions. Exception handlers are contained in catch blocks. One or more
catch blocks immediately follow the try block. Each catch block specifies
the type of exception it can catch and handle. Each catch block is an
exception handler.

Institute of Petrochemical Engineering, Lonere

20

Project Report

Chat Server

Class thread:
Class thread (package java.lang) has several constructors. The
constructor public Thread (string threadName) constructs a Thread objects
whose name is threadName. The constructor public Thread constructs a
Thread whose name is Thread concatenated with a number, like Thread-1,
Thread-2 and so on.
The code that does the real work of a thread is placed in its run
method. The run method can be overridden in a subclass of Thread
A program launches a threads execution by calling the threads start
method, which in turn, calls the run method. After start launches the thread,
start returns to its caller immediately. The caller then executes concurrently
with

the

launched

thread.

The

start

method

throws

an

IllegalThreadStateException. If the thread it is trying to start has already


been started. A thread enters the dead state when its run method completes
or terminates for any reason; a dead thread will eventually be disposed by
the system.
Class thread is extended to create new classes that support
multithreading. We overrode the run method to specify the tasks to be
performed concurrently. If we want multithreading supported in a class that
is already derived from a class other than thread we must implement the
Runnable interface in that class. Class Thread itself implements the
Runnable interface (package java.lang) as expressed in the class header
public class Thread extends object implements Runnable. Implementing the
Runnable interface gives us the ability to treat our new class as a Runnable
object (just like inheriting from a class allows us to treat our subclass as an
object of its super class). As with deriving from the Thread class, the code

Institute of Petrochemical Engineering, Lonere

21

Project Report

Chat Server

that controls the thread is placed in the run method. We create a thread with
the new class by passing to the Thread class constructor public Thread
(Runnable runnableobject)
A reference to an object of the class that implements the Runnable
interface. The Thread constructor registers the run method of the
runnableobject as the method to be invoked when the thread begins
execution.
3.2 Graphical User Interface(GUI):
BASIC GRAPHICAL USER INTERFACE COMPONENT:

A graphical user interface (GUI) presents a pictorial interface to a


program. A GUI gives a program a distinctive look and feel. By
providing different applications with a consistent set of intuitive user
interface components, GUIs allow the user to spend less time trying to
remember which keystroke sequences do what and spend more time using
the program in a productive manner.

Some Basic GUI Component: -

Institute of Petrochemical Engineering, Lonere

22

Project Report

Chat Server

Component
Description
JLabel
An area where uneditable text or icons can
JTextField

be displayed.
An area in which the user inputs data from
the keyboard. The area can also display

JButton
JCheckBox

information.
An area that triggers an event when clicked.
A GUI component that is either selected or

not selected.
JComboBox A drop-down list of items from which the
user can make a selection by clicking an
item in the list or by typing into the box, if
JList

permitted.
An area where a list of items displayed from
which the user can make a selection by
clicking once on any element in the list.
Double Clicking an element in the list
generates an action event. Multiple elements

JPanel

can be selected.
A container in which components can be
placed.

3.6.1.Swing Overview: The classes that are used create the GUI components are part of the
Swing GUI components from package javax.swing. These are the newest
GUI components of the Java 2 platform. Swing components are written,
manipulated and displayed completely in java (so called pure Java
components).

Institute of Petrochemical Engineering, Lonere

23

Project Report

Chat Server

The original GUI components are from the Abstract Windowing


Toolkit package java.awt are tied directly to the local platforms graphical
user interface capabilities. So, a java program executing on different java
platforms has a different appearance and sometimes even different user
interactions on each platform. Together, the appearance and how the user
interacts with the program are known as that programs look and feel. The
swing component allowed the programmer to specify a different look and
feel for each platform, or a uniform look and feel across all platforms, or
even to change the look and feel while the program is running.
Swing component are often referred to as light-weight componentthey are written completely in java so they are not weight down by the
complex GUI capabilities of the platform on which they are used. AWT
components that are tied to the local platform are correspondingly called
heavyweight component- they rely on the local platforms windowing
system to determine their functionality and look and feel. Each heavyweight
component has a peer that is responsible for the interactions between the
component and local platform to display and manipulate the component.
Several swing components are still heavyweight component. In particular,
subclasses of the java.awt.Window that display windows on the screen still
require direct interaction with the local windowing system. As such,
heavyweight Swing GUI component are less flexible than many of the
lightweight components.
Figure 3.6.1 shows an inheritance hierarchy of the classes that define
attributes and behaviors that are common to most swing components. Each
class is display with its fully qualified package name and class name. Much
of the GUI components functionality derived those classes. A class that
inherits from the component class is a component. For example, class
Institute of Petrochemical Engineering, Lonere

24

Project Report

Chat Server

Container inherits from class Component, and class Component inherits


from Object. Thus, a Container is a Component and is an Object, and a
Component is an Object. A class that inherits from class Container is a
Container. Thus, a JComponent is a Container.
java.lang.Object
java.awt. omponent
java.awt.Container

javax.swing.JComponent

Fig 3.6.1 common super classes of many of the swing component.


Class Component defines the methods that can be applied to an object
of any subclass of Component. Two of the methods that originate in class
Component have been used frequently to this point in the text- paint and
repaint. It is important to understand the methods of class Component
because much of the functionality inherited by every subclass of Component
class originally. Operations common to most GUI components are found in
class Component.
A class Container is a collection of related components, in application
with JFrames and in applets; we attach components to the content pane- a
Container. Class Container defines the set of methods that can be applied to
an object of any subclass of Container. One method that originates in class
Container that has been used frequently to this point in the text is add for
adding components to the content pane. Another method that originates in

Institute of Petrochemical Engineering, Lonere

25

Project Report

Chat Server

class Container is setLayout, which has been used to specify the layout
manager that helps a Container position and size its components.
Swing component that subclass JComponent have many features, including:
i.

A pluggable look and feel that can be used to customized the look and
feel when the program executes on different platforms.

ii.

Shortcut keys for direct access to GUI components through the


keyboards.

iii.

Common event handling capabilities for cases where several GUI


components initiate the same actions in a program.

iv.

Brief description of a GUI components purpose that are displayed


when the mouse cursor is positioned over the component for the short
time.

v.

Support for assertive technologies such as Braille screen readers for


blind people.

vi.

Support for user interface localization-customizing the user interface


for display in different languages and cultural conventions

3.6.2.Event Handling Model:


GUIs are event driven. Some common interactions are moving the
mouse, clicking the mouse, clicking a button, typing in a text field, selecting
an item from a menu, closing a window etc. when a user interaction occurs,
an event is automatically sent to the program. GUI event information is
stored in an object of a class that extends awtEvent. Fig 3.6.2 illustrates a
hierarchy containing many of the event classes we use from package
java.awt.event. The event types from package java.awt.event are still used
with the swing components. Additional event types have also been added

Institute of Petrochemical Engineering, Lonere

26

Project Report

Chat Server

that are specific to several types of swing components. New swing


component event types are defined in package javax.swing.event.
To process a graphical user interface event, the programmer must
perform two key tasks register an event listener and implement an event
handler. An event listener for a GUI event is an object of a class that
implements one or more of the event listener interfaces from package
java.awt.event and package javax.swing.event. Many of the event listener
types are common to both swing and AWT components. Such types are
defined in package java.awt.event. Additional event types are specific to
swing components are defined in package javax.swing.event. An event
listener object listens for specific types of events generated in the same
object or by other objects in a program. An event handler is a method that is
automatically called in response to a particular type of event. Each event
listener interface specifies one or more event handling methods that must be
defined in the class that implements the event listener interface. Remember
that interfaces define abstract methods. Any class that implements an
interface must define all the methods of the interface; otherwise, the class is
an abstract class and cannot be used to create objects. The use of event
listeners in event handling is known as the delegation event model the
processing of an event is delegated to a particular object in the program.
When an event occurs, the GUI component with which the user
interacted notifies its registered listeners by calling each listeners appropriate
event handling method. For example, when the user process the enter key in
a JTextField, the registered listeners actionPerformed method is called.

Institute of Petrochemical Engineering, Lonere

27

Project Report

Java.lang.Object

Java.util.EventObject

Java.awt.AWTEvent

Chat Server

AdjustmentEvent

FocusEvent

ItemEvent

PaintEvent

ComponentEvent

WindowEvent
InputEvent

keyEvent

mouseEvent

Fig 3.6.2 some event classes of package


java.awt.event
JTextField and JPasswordField:
JTextFields and JPasswordFields are single line areas in which the
user can enter text from the keyboard or text can simply be displayed. A
JPasswordField shows that a character was typed as the user enters
characters, but hides the characters assuming that they represent a
password that should remain known only to the user.
Institute of Petrochemical Engineering, Lonere

28

Project Report

Chat Server

When the user types data into a JTextField or JPasswordField can be


used in the program. Class JTextField extends class JTextComponent,
which provides many features common to swing text-based components.
Class JPasswordField extends JTextField and adds several methods that
are specific to processing passwords.

JLabel:
Labels provide text instructions or information on a GUI. Labels are
defined with class JLabel a subclass of JComponent. A label displays a
single line of read only text. Once labels are created, programs rarely
change a labels contents.

JButton:
A button is a component the user clicks to trigger a specific action. A
java program can use several types of buttons, including command
buttons, check boxes, toggle buttons and radio buttons. A command
button generates an ActionEvent when the user clicks the button with the
mouse. Command buttons are created with class JButton, which inherits
from class abstracts Button. The text on the face of a JButton is called a
button label. A GUI can have many JButtons, but each button label
should typically the unique.
JList:

Institute of Petrochemical Engineering, Lonere

29

Project Report

Chat Server

A list displays a series of items from which the user may select one or
more items. Lists are created with class JList, which inherits from class
JComponent. Class JList supports single selection lists
Panels:
Complex GUIs require that each component be placed in an exact
location. They often consist of multiple panels with each panel
components arranged in a specific layout. Panels are created with class
JPanel a subclass of JComponent. Class JComponent inherits from claas
java.awt.Container, so every JPanel is a Container. Thus JPanels may
have components, including other panels, added to them.

JTextArea:
JTextArea provide an area for manipulating multiple lines of the text.
Like class JTextField, class JTextArea inherits from the JTextComponent,
which defines common methods for JTextField, JTextAreas and other
several text-based GUI component.

Layout Managers:
Layout managers are provided to arrange GUI components on a
container for presentation purposes. The layout managers provide basic
layout capabilities that are easier to use than determining the exact

Institute of Petrochemical Engineering, Lonere

30

Project Report

Chat Server

position and size of every GUI component. This enables the programmer
to concentrate on the basic look and feel and lets the layout managers
process most of the layout details.
Layout
manager
FlowLayout

Description
Default for java.applet.Applet java.awt.panel and
javax.swing.JPanel places components sequentially
in the order they were added .it is also possible to
specify the order of the components using the
container method add that takes a component and an

BorderLayout

integer index position as arguments


Default for the content panes of JFrames and
JApplets. Arrange the components into five areas:

GridLayout

north, south, east, west and center


Arranges the components into rows and columns.

FlowLayout:
FlowLayout is the most basic layout manager. GUI components are
placed on a container from left to right in the order in which they are
added to the container. When the edge of the container is reached,
components to be left aligned centered and right aligned.
BorderLayou:t
The BorderLayout layout manager arranges components into five
regions. North, South, East, West and Center. Class BorderLayout
inherits from object and implements interface LayoutManager. Up to five
Institute of Petrochemical Engineering, Lonere

31

Project Report

Chat Server

components can be added directly to a BorderLayout one for each region.


The components placed in the North and South regions extend
horizontally to the sides of the container and are as tall as the North and
South regions and are as wide as the components placed in those regions.
The component placed in the Center region expands to take all remaining
space in the layout. If all regions are occupied, the entire containers space
is covered by GUI components. If the North or South region is not
occupied, the GUI components in the East or West regions expand
vertically to fill the remaining space. If the East or West region is not
occupied, the GUI component in the Center region expands horizontally
to fill the remaining space. If the Center region is not occupied, the area
is left empty the other GUI components do not expand to fill the
remaining space.
GridLayout:
The GridLayout layout manager divides the container into a grid so
that components can be placed in rows and columns. Class GridLayout
inherits

directly

from

class

object

and

implements

interface

LayoutManager. Every Component in a GridLayout has the same width


and height. Components are added to a GridLayout starting at the top left
cell of the grid and proceeding left to right until the row is full. Then the
process continues left to right on the next row of the grid.

3.6.3.Adapter Classes:

Institute of Petrochemical Engineering, Lonere

32

Project Report

Chat Server

Many of the event listener interfaces provide multiple methods;


MouseListener and MouseMotionListener are examples. It is not always
desirable to define every method in an event listener interface. For example
a program may only need the mouse-clicked handler from interface
MouseListener or the MouseDragged handler from MouseMotionListener.
In our windowed applications terminating the application has been handled
with windowClosing from interface windowListener, which actually
specifies seven window event-handling methods. For many of the listener
interfaces that contain multiple methods, package java.awt.event and
package javax.swing.event provide a default implementation of every
method in the interface. The programmer can extend the adapter class to
inherit the default implementation of every method then override the method
needed for event handling. The default implementation of each method in
the adapter class has an empty body.
3.7.Files and Stream:
Java views each file as a sequential stream of the byte. Each file ends
either with an end-of-file marker or at a specific byte number recorded in a
system maintained administrative data stricture. When a file is opened, an
object is created and a stream is associated with the object. Three objects are
created for us automatically when we begin executing java programSystem.in, System.out, System.err.

The streams associated with these

objects provide communication channel between the program and the


particular file or a device. For example Object System.in (standard input
stream object) enables a programs to input byte from the keyboard, object
System.out (standard output stream object) enable a program to output data
to the screen, and the object System.err (standard error stream object)

Institute of Petrochemical Engineering, Lonere

33

Project Report

Chat Server

enables a program to output error messages to the screen. Each of these


streams can be redirected.

3.7.1.The stream classes:


Javas stream-based I/O is built upon four abstract classes
InputStream, OutputStream, Reader and Writer. They are used to create
several concrete stream subclasses. The tops level classes define the basic
functionality common to all stream classes.
InputStream and OutputStream are designed for byte streams. Reader
and Writer are designed for character streams. The byte stream classes and
the character stream classes form separate hierarchies. In general you should
use the character stream classes when working with characters or strings.
To perform file processing in java, the java package java.io must be
imported. This package includes definition for the stream classes such as
FileInputStream (for a input from a file) and FileOutputStream (for a output
to a file). Files are created by objects of these classes that inherit from the
classes InputStream and OutputStream. The method of these streams can be
applied to a file stream as well.
InputStream (a subclass of object) and OutputStream (a subclass of
object) are abstract classes that define methods for performing input and
output respectively. A PrintStream is a used for performing output to the
screen.
3.7.2.BufferedReader:
Buffered Reader improves performance by buffering input. It has two
constructors.
BufferedReader (Reader inputStream)

Institute of Petrochemical Engineering, Lonere

34

Project Report

Chat Server

BufferedReader (Reader inputStream,int bufSize)


The first form creates a buffered character stream using a default
buffer size. In the second, the size of the buffer is passed in bufsize.
3.8.An Overview of Java Database Connectivity:
Database systems not only provide file-processing capabilities, they
organize data in manner that facilitates satisfying sophisticated queries. The
most popular style of the database system on the kinds of computers that use
java is the relational database. Object-oriented databases are have also
become in recent year. A language called Structured Query Language (SQL)
is almost universally used among relational database Systems to make
queries. Java enables programmers to written code that uses SQL queries to
access the information in relation database systems. Some popular relational
database packages include Microsoft Access, Sybase, Oracle, and Informix,
Microsoft SQL server.
Suppose you have a set of records in an Access database that you have
to view through a front-end tool. You can design a user interface by using
various programming languages such as Visual Basic, Visual C++, etc. Java,
however, provides a more consistent approach in developing these interfaces
through the javax.swing package. Moreover, Java provides the Java
Database Connectivity (JDBC) API, with which you can connect your app to
any database, designed either using Microsoft Access or SQL Server. In this
article, we will examine the basic steps required to handle JDBC using
javax.swing for creating user interfaces.
Before proceeding further, let us take a quick look at Microsoft's
Object Database Connectivity (ODBC) and the preference of JDBC over
Institute of Petrochemical Engineering, Lonere

35

Project Report

Chat Server

ODBC. The ODBC API offers connectivity to almost all databases on almost
all platforms and is the most widely used programming interface for
accessing relational databases. But ODBC cannot be used directly with Java
programs due to various reasons.
ODBC uses a C interface. This has drawbacks in security,
implementation, robustness, etc. ODBC makes use of pointers (which have
been removed from Java).
Hence JDBC came into existence. If you've done database
programming using Visual Basic, then you will be familiar with ODBC. You
can connect a VB application to an Access database or an Oracle table
directly via ODBC. Since Java is a product of Sun Microsystems, you have
to make use of JDBC along with ODBC in order to develop Java database
applications. JDBC is a set of Java APIs for executing SQL statements. This
API consists of a set of classes and interfaces to enable programmers to
write pure database applications.
Advantages of database systems

Following are the several important advantages of database


systems.

Redundancy can be reduced.

Inconsistency can be avoided.

The data can be shared.

Standards can be enforced.

Security restrictions can be applied.

Institute of Petrochemical Engineering, Lonere

36

Project Report

Chat Server

Integrity can be maintained.

Conflicting requirements can be balanced.

In non-database systems, each distinct application maintains its own


files, often with considerable redundancy and a variety of physical formats.
In database systems, integrating separate files reduces redundancy. Sharing
is one of the most important benefits of database systems. Existing
applications can reference the same data. Security is an intriguing issue in
database systems. The data may actually be more at risk because it is
collected and retained in a central location rather than being dispersed
through physically separate files in many locations. To counter this, database
systems must be designed with elaborate access controls.
Let us now examine the basic steps required in all Java programs to handle
JDBC.
Step 1: Loading Drivers
First, you have to load the appropriate driver. You can use one
driver from the available four. However, the JDBC-ODBC driver is
the most preferred among developers. In order to load the driver, you
have to give the following syntax:
Class.ForName ("sun.jdbc.odbc.JdbcOdbcDriver");

Step 2: Making a Connection


The getConnection() method of the Driver Manager class is
called to obtain the Connection object. The syntax looks like this:
Connection conn = DriverManager.getConnection ("jdbc:odbc:<DSN
NAME>");
Institute of Petrochemical Engineering, Lonere

37

Project Report

Chat Server

Here, note that getConnection() is a static method, meaning it should


be accessed along with the class associated with the method. You have
to give the Data Source Name as a parameter to this method. (See
section below for setting up the Data Source Name in your computer.)
Step 3: Creating JDBC Statements
A Statement object is what sends your SQL Query to the
Database Management System. You simply create a statement object
and then execute it. It takes an instance of active connection to create
a statement object. We have to use our Connection object "conn" here
to create the Statement object "stmt". The code looks like this:
Statement stmt = conn.createStatement();

Step 4: Executing the Statement


In order to execute the query, you have to obtain the Result Set
object (similar to Record Set in Visual Basic) and a call to the
executeQuery() method of the Statement interface. You have to pass a
SQL query like select * from students as a parameter to the
executeQuery() method. If your table name is different, you have to
substitute that name in place of students. Actually, the Record Set
object contains both the data returned by the query and the methods
for data retrieval. The code for the above step looks like this:
ResultSet rs = stmt.executeQuery ("select * from students");
If you want to select only the name field, you have to issue a SQL
command like Select Name from Student. The executeUpdate()
method is called whenever there is a delete or an update operation.

Institute of Petrochemical Engineering, Lonere

38

Project Report

Chat Server

Step 5: Looping Through the ResultSet


The ResultSet object contains rows of data that is parsed using
the next() method, such as rs.next(). We use the getXXX() method of
the appropriate type to retrieve the value in each field. For example, if
your first field name is ID, which accepts Number values, then the
getInt() method should be used. In the same way, if the second field
Name accepts integer String values, then the getString() method
should be used, like the code given below:
System.out.println (rs.getInt("ID"));
Step 6: Closing the Connection and Statement Objects
After performing all the above steps, you have to close the
Connection and RecordSet objects appropriately by calling the close()
method. For example, in our code above, we will close the object as
conn.close()and statement object as stmt.close().

4. System Analysis
Institute of Petrochemical Engineering, Lonere

39

Project Report

Chat Server

4.1.Flow of Chat-Server:
As the name suggests chat-server means, multiple users can chat with
each other. For that purpose, we have invented a concept server and client. A
server is nothing but a program, which handles the communication between
clients using the server socket class. What we have planned is we made a
simple program for server, which takes the entire request from users and
fulfill it. We made program for client, who only generates a request to server
and receive a fulfilled reply from server.
Server does the following things:
After you start the server program, it will look for the clients, which
want to connect to server. The lines of code for this purpose is:
If (server! =null)
{
System.out.println (listening for clients);
}
while (true)
{
socket client =server.accept();
in

=new

BufferReader(new

InputStreamReader(client.getInputStream()));

Institute of Petrochemical Engineering, Lonere

40

Project Report

Chat Server

Stream receivedString= ;
while (receivedString.equals( ))
{
receivedString=in.readLine();
}
If server finds any of the clients want to connect to server, it will
create a clientThread for a particular client. The thread maintains all the
communication made from server. When we create a clientThread, the
reference of server is being passed.
The clientThread runs continuously to see request received from
particular client. To distinguish between requests, we made proper protocol
with request. E.g.: Suppose one client wants to chat with others, the request
from client will be CMD_SEND_MESSAGE+from user+actual chat
message. From this, we can easily understand that what request has been
passed and now how to process on that request. We have written the methods
like sendMessageToAll(), sendMessage(), getIndex(), setIndex() for several
purpose. The sendMessageToAll() method takes a string parameter and it
calls the servers broadcast method.
To understand the servers broadcast method, the code is
public void broadcast(String msg)
{

Institute of Petrochemical Engineering, Lonere

41

Project Report

Chat Server

System.out.println(while bradcasting+clients.size());
for(int I=0;I<clients.size();I++)
{
clientThread c=(clientThread)client.elementAt(i);
c.sendMessage(msg);
}
}
Once client connects the server, server makes a entry in vector called
clients, because server has to look after all clients at a given time.
The broadcast method takes all the clients from client vector. Client
vector hold the clientThread. Once it gets all the clientThread, the
clientThread send message() method get in activation which does the
following.
The sendMessage()code should be written here:
public void sendMessage(String msg)
{
this.out.println(msg);
this.out.flush();
}

Institute of Petrochemical Engineering, Lonere

42

Project Report

Chat Server

In this method, actual message is sent to the actual clientWindow.


Now suppose, client want to log-off the proper message is sent from
client. At the server side, server made that client from clients vector and
stops that thread.
It took the name of user/client as a parameter. Where we install a
copy of clientWindow program, we have to keep a file called client.ini. This
file contains the actual name of server. It is nothing but the name of
computer where our server program is running. We invented this file because
when we want to change the server, we need not modify the server and client
window class. The client window program connects server using following
lines of code:
public ClientWindow (String userName)
{
initComponents ();
this.userName =userName;
try {
BufferedReader br =new BufferedReader (new InputStreamReader
(new FileInputStream (client.ini)));
client =new Socket (computerName,16000);
this.setTitle (userName);

Institute of Petrochemical Engineering, Lonere

43

Project Report

in

Chat Server

=new

BufferedReader

(new

InputStreamReader

(client.getInputStream()));
out =new PrintWriter (client.getOutputStream());
String sendString =CMD_GET_USER_LIST:;
out.println (sendString+userName);
out.flush ();
String receivedString =;
while (receivedString.equals ( )){
receivedString =in.readLine ();
}
}
When clientWindow connects to server, it sends the request of
currently logged clients. The server program processes using the clients
vector and sends the list of users using proper protocol that can be easily
understand by clientWindow program. When a client is generated, one
serverThread is generated to manipulate communication between this client
and server. Actually the clientThread and serverThread classes are logically
the same. They evolved for the same purpose.
The login class is made to log in the users. The user/client has to enter
valid username and password to access the chat server. Once user enters a

Institute of Petrochemical Engineering, Lonere

44

Project Report

Chat Server

valid user and password, the client window comes in activation. The rest of
the project is managed by both clientWindow and server class.
To manipulate users operations like adding of users, changing the
passwords of existing users and validating the username and password. We
build basic class users. The users class directly manipulates the database. It
has methods like add(), edit(), delete(), update() and find() method to work
on particular user. When user want to log in the chat server the users find
method comes in picture. It gives the record from user, but the name of
computer where our server program is running.

4.2.Data Flow Diagram:


start

server started

server is listening for clients

client started

Institute of Petrochemical Engineering, Lonere

45

Project Report

Chat Server

client connected using password


and ID

server checks clients validity

client process
terminate.

validity

false
Chat window is
open for chatting

true
clients chat with
each other.

If any client
wants to logout
then cliks on
logout button.

client process
terminate.

end

Institute of Petrochemical Engineering, Lonere

46

Project Report

Institute of Petrochemical Engineering, Lonere

Chat Server

47

Project Report

Chat Server

5. Implementation
Figure 5.1 shows the server window, which is always listening for clients.

Figure 5.1

Figure

5.2

shows client
window. In
this

client

window user
must enter his/her ID & password for entering into chat window. When
password does not match with password, which is stored in database, then
server sends password does not agree message.

Figure 5.2

Institute of Petrochemical Engineering, Lonere

48

Project Report

Chat Server

Figure 5.3 shows client window when password match with the password
stored in the database then server opens chat window for that client.

Figure 5.3
Figure 5.4 shows the chat window in which number of clients can chat with
each other. In this window three clients are enter for chat. Names of those
clients are displayed on the right side of window. Incoming messages from
those clients are displayed on the upper side of the window.

Institute of Petrochemical Engineering, Lonere

49

Project Report

Chat Server

Figure 5.4
Figure 5.5 shows the window for enter new user. If new user enter then that
users ID & password is stored into database of the server.

Figure 5.5
Figure 5.6 shows new user that is enter for chat.

Institute of Petrochemical Engineering, Lonere

50

Project Report

Chat Server

Figure 5.6

Figure 5.7 shows the window for change the password of user.

Figure.5.7
Institute of Petrochemical Engineering, Lonere

51

Project Report

Chat Server

6. Application and Future Scope

6.1.Types of Chat Server:


6.1.1.Yahoo Chat:
Yahoo offers its members a wide range of services including chat.
Their chat supports both HTML and Java applet clients. Unfortunately, their
chat software is proprietary, so companies cannot incorporate their
community model with Yahoo's chat software.
6.1.2.DigiChat:
DigiChat is a standalone Java chat application. It offers a well thought
out chat client interface and also supports moderated chats. However like
most third party applications, there are no easy means by which Digichat can
be integrated with a site's preexisting user data model. DigiChat also comes
with a heavy price tag, and as such it might not be suitable for a small
communities that need to support chat sessions.
The ArsDigita Java Chat application does not have a pretty client
interface, nor does it support text formatting like Yahoo and Digichat.
However, our Chat application is open source. As such, any competent Java
developer will be able to improve the interface based upon their or their
employer's preferences. Using the ArsDigita Chat application allows site
developers access to a rich community data model, which is compatible with
a variety of existing open-source applications.

Institute of Petrochemical Engineering, Lonere

52

Project Report

Chat Server

7. Conclusion
As the name suggests chat-server means, multiple users can chat with
each other. For that purpose, we have invented a concept server and client. A
server is nothing but a program, which handles the communication between
clients using the server socket class. What we have planned is we made a
simple program for server, which takes the entire request from users and
fulfill it. We made program for client, who only generates a request to server
and receive a fulfilled reply from server.

Institute of Petrochemical Engineering, Lonere

53

Project Report

Chat Server

Reference
1. Java: How To Program: - Third edition
By Deitel and Deitel.
2. The Complete Reference of Java: - Fifth edition

Institute of Petrochemical Engineering, Lonere

54

Project Report

Chat Server

By Herbert Schield.

Institute of Petrochemical Engineering, Lonere

55