Sie sind auf Seite 1von 168

Online Chat Client-Using TCP/IP Client Model

by
G E L R Naga Prasad

Under The Esteemed Guidance of

Submitted to the school of computer and information sciences

In partial fulfillment of the requirements

For the degree of

Masters of Computer Applications

INDIRA GANDHI NATIONAL OPEN UNIVERSITY

New Delhi
PROFORMA OF PROJECT PROPOSAL

SCHOOL OF COMPUTER AND INFORMATION SCIENCES


IGNOU, MAIDAN GARHI, NEW DEHLI – 110 068

PROFORMA FOR SUGGESTIONS OF MCS-044 PROJECT PROPOSAL

(Note: All entries of the proforma of suggestions should be filled in with appropriate and complete
information. Incomplete proforma of suggestions in any respect will be summarily rejected.)

Enrolment No.: 072257657

Study Centre: Aurora’s Degree College, Chikkadpally, Hyd-500020

Regional Centre: Hyderabad RCCode: 01

E-mail: prasad_g22@yahoo.co.in

Telephone No.: +91-9959054164

1. Name and Address of the student:: G E L R Naga Prasad

S/o G N Prabhuji,

Plot no-117, Sri Rama RTC Colony,

Opp Saibaba temple,

Medipally, R R Dist-500039.

2. Title of the Project: Online Chat Communicator

3. Names and Address of the Counselor:

4. Educational Qualification of the Counselor

Ph.D* M.Tech* BE*/B.Tech* MCA M.Sc.*

(* in Computer Science/IT only)


5. Working/Teaching Experience of the Counsellors**:

6. Software used in the Project.

Programming Language: Java is used to create the project. We have used the server socket-
programming feature, which enables the Client/Server Architecture ability.
Front-end development: The front end is proposed to be developed on Java platform using
the netbeans IDE 5_5_1 as the Java Native Client. We are proposing to design the Front end as Applet
and the Server is also designed the same way. The communication between the server and the client
follows the TCP/IP protocol.

Back-end development: We have proposed to have the back end on the local drive in case of
clients. Since if a client when desires to save the data, then he could save the data log in the Html
Format into his/her local machine. On the other hand the sever could keep the track of all the
transactions that are made between the clients. Hence the server could also keep the log file saved in
the HTML format.

Please see that we are not incorporating the Auto save log feature of the Chat Client.

Hardware Requirements: Keeping the Technical specification in our mind we have


designed the following hardware requirements in our project.

@A T1 cable Lan Network for deploying the server and the Client

@ JDK 1.6 version to be installed in the system, because the Jar Files would not nun if the following
version is not installed

@ All the systems must have configuration at least above P3 configurations. So that the speed of the
application would remain intact.

Signature of the Student Signature of the Counsellor

Date: Date:

************************************************************************

Suggestions for improving the Project:


CERTIFICATE OF AUTHENTICATED WORK

This is to certify that the project report entitled “Online Chat Client” submitted to Indira Gandhi
National Open University in partial fulfilment of the requirement for the award of the degree of
Master of Computer Applications (MCA) is an original work carried out by G E L R Naga Prasad
Enrolment No. 072257657 under my guidance. The matter embodied in this project is authentic and
is genuine work done by the student and has not been submitted whether to this University or to any
other University/ Institute for the fulfilment of the requirement of any course of study.

……………….. ………………………………….

Signature of the Student Signature of the Counsellor

Date : ……..……… Date : …………………

Name and Address of the Name, Designation and Address of the

Student Counsellor

G E L R Naga Prasad

S/o G N Prabhuji,

Plot no-117, Sri Rama RTC Colony,

Opp Saibaba temple,

Medipally, R R Dist-500039.

Enrolment No: 072257657


ROLES AND RESPONSIBILITIES FORM

Name of the Project: Online Group Chat Communication.

Date: 1st July,2009

Name of the Member * Role Tasks and Responsibilities

Khushboo Savadia Team Coordinator, Quality Overall Quality Management of


Manager project. Collection of Metrics,
and Meeting the Deadlines

Manish Mitra Developer/System Analyst Developing the Code and


Maintaing the System

Rajini Test Analyst Creating the Test Documents


Required for the Project
G E L R Naga Prasad

Name and signature of the Project Team Members:

1. Manish Mitra Signature ……………………………………….

2. Khushboo Savadia …….…………………………………..

3. Rajini ………………………………………….

4. G E L R Naga Prasad ..…..……………………………………..

Signature of the Counselor …………………………………. Date…………………….

* Students may take up roles such as Team Coordinator, Auditor/Receiver, Data Manager, Quality
Manager or others according to the needs of the project
ABSTRACT

Group Communication

Introduction to Networking

A Network is simply a collection of computers or other hardware devices that are connected together,
either physically or logically, using special hardware and software, to allow them to exchange
information and cooperate. Networking is the term that describes the processes involved in designing,
implementing, upgrading, managing and otherwise working with networks and network technologies.
Computer networks differ in their design. The two types of high-level network design are called
client-server and peer-to-peer. Client-server networks feature centralized server computers that store
email, Web pages, files and or applications. On a peer-to-peer network, conversely, all computers tend
to support the same functions.

The following characteristics are also used to categorize different types of networks:

• Topology: The geometric arrangement of a computer system. Common topologies include a


bus, star, and ring.

• Protocol: The protocol defines a common set of rules and signals that computers on the
network use to communicate. Popular protocols for LANs are Ethernet, token-ring network.

• Architecture: Networks can be broadly classified as using either a peer-to-peer or client/server


architecture.

• Geographic area: Local area networks (LANs), Metro Area Networks (MANs), Wide area
networks (WANs), reach across.

Instant Messaging
Instant messaging (IM) is a form of online communication that allows real-time (or close to real-time)
interaction through personal computers or mobile computing devices. Users can exchange messages
privately, similar to e-mail, or join group conversations. Although typed text remains the primary
convention for IM, the technology has grown significantly from early versions and now allows users
to send images, audio and video files, and other attachments. Early versions of IM appeared in the late
1990s, and the list of IM tools has grown to include dozens of applications. Technologies that enable
IM—such as wireless connectivity and mobile devices—have become widespread, providing a
“critical mass” for IM to reach near ubiquity. At the same time, many vendors whose primary
business is something other than IM have added IM functionality to their products.

Nearly all-learning management systems have incorporated chat tools, ranging from the elegant and
sophisticated, which include icons, sounds, and pictures, to the rudimentary, which simply provide
text in boxes. The interactive nature of IM is closer to spoken conversation than written
correspondence, allowing users to communicate in a manner that e-mail does not. At the same time,
the technology facilitates the kind of on-screen interaction, with its perceptions of distance and safety.

Functionality ranges widely for IM applications, but typically users log in to a service with a screen
name or ID. Most IM applications notify users when others join or leave, and many allow users to
indicate their status, for example “away from desk” or “in a meeting.” Once logged in, users can send
messages to individuals or join IM sessions. Most IM windows include an area where messages are
displayed chronologically and a composition box where messages are typed. Composition boxes
usually allow basic formatting of text, and most let users add images, multimedia files, or other
attachments. When someone types an instant message, the chat client indicates that a message is being
composed.

Chat Server is a computer dedicated to providing the processing power to handle and maintain
chatting and it users.

Technical Specifications:

Programming Language: Java is used to create the project. We have used the server socket-
programming feature, which enables the Client/Server Architecture ability.

Front-end development: The front end is proposed to be developed on Java platform using
the netbeans IDE 5_5_1 as the Java Native Client. We are proposing to design the Front end as Applet
and the Server is also designed the same way. The communication between the server and the client
follows the TCP/IP protocol.
Back-end development: We have proposed to have the back end on the local drive in case
of clients. Since if a client when desires to save the data, then he could save the data log in the
Html Format into his/her local machine. On the other hand the sever could keep the track of all
the transactions that are made between the clients. Hence the server could also keep the log file
saved in the HTML format.
Please see that we are not incorporating the Auto save log feature of the Chat Client.

Hardware Requirements: Keeping the Technical specification in our mind we have


designed the following hardware requirements in our project.

@A T1 cable Lan Network for deploying the server and the Client

@ JDK 1.6 version to be installed in the system, because the Jar Files would not nun if the following
version is not installed

@ All the systems must have configuration at least above P3 configurations, so that the speed of the
application would remain intact.

Overview of the Project

Connection Procedure:

We are planning to have a server with n number of nodes to attach to the system. The server will have
one of the server-programming running on it. Servelet would be a normal choice in this case.

The client attached to the node will also have the client side-programming running, which would be
running as an applet. Usage of Swing components would be a better choice since swings as we know
is a Light Weight Object.

The Client would request for an account from the Server with the help of the IP Address of the Server.
Before entering to this we will first run the Servelet on the server and associate it with a PORT. So
any client who is getting connected to the server would be required to give the Port as well as the IP
address of the server.

This should be one case by which we could connect the other case would be connecting through the
Computer Name. Since we know that when a system is connected into a network, it is associated with
a computer name and hence if any Server-Client interaction has to be made with that Client, the
computer name is used for it. In our case we could use the server name as the Computer Name to
connect to the server.

Communication Procedure:

We have used the TCP/IP protocol to leverage the communication between the nodes in the network.
Every node in a network is represented by a IP and the same is used to Communicate. The server is
bounced through a Port (a number rather) and the same port is used by the client to communicate. It
should be noted that only one client could communicate to multiple clients at one instance.

We are not having any encryption of data. So security of the data could be one threat to the project.
Encryption could be imbibed in the future releases.

Technically the server routes the data to the client by the node selection made by the client. This we
are planning to do with the help of Vector Selection.

The Log data could be saved by the client on their machine and the format would be in HTML file.
This could be accessed by the User for their future purpose.

Acknowledgement

I would like to acknowledge the contributions of the following groups and individuals to the
development of my Project:

Mr Suraj:
Mr. Suraj directed me to a wide range of resources on the web. He answered all of my questions as
well as asked me questions that helped me to narrow my search. Further, He helped me figure out
correct documentation for sources that did not fit the Research Guide examples. He gave me this help
during class time and after school. I also worked with my fellow colleagues at Oracle who helped me
locate primary sources and to carry out the project smoothly.
TABLE OF CONTENTS

S.No Description
CHAPTER: 1. INTRODUCTION (A Brief about the Project)
1.1 Background

1.2 Objectives

1.3 Purpose, Scope

1.3.1. Purpose

1.3.2. Scope

CHAPTER: 2. SURVEY OF TECHNOLOGIES


2.1 TCP/IP Model Architecture

2.2 UDP Protocol

2.3 Java - J2EE Architecture

2.4 J2EE Platform and Applications

2.5 Project Management Stylus

2.6 Which Protocol Must Be Used ? TCP/IP or UDP!!

CHAPTER: 3. REQUIREMENTS AND ANALYSIS


3.1 Problem Definition

3.2 Requirements Specification

3.3 Planning and Scheduling

3.3.1 Pert chart

3.3.2 Gantt chart (bar chart)

3.4 Software and Hardware Requirements

3.4.1 Hardware Requirement

3.4.2 Software Requirement

3.5 Preliminary Product Description


3.6 Conceptual Models

CHAPTER: 4. SYSTEM DESIGN


4.1 Basic Modules

4.2 Procedural Design

4.3 Test Case Design

CHAPTER: 5. IMPLEMENTATION AND TESTING


5.1 Implementation Approaches

5.2 Coding Details and Code Efficiency

5.3 Testing Approach

5.3.1 Unit Testing

5.3.2 Integrated Testing

5.3.3 System Testing

5.3.4 Acceptance Testing

5.3.5 Test Plan

CHAPTER: 6. RESULTS AND DISCUSSIONS


6.1 Test Reports

6.2 User Documentation

CHAPTER: 7. CONCLUSIONS
7.1 Conclusion

7.2 Limitations of the System

7.3 Future Scope of the Project


Table of Figures
Sno Figure Description Page Number
1 TCP/IP ARCHITECTURAL MODEL 15

2 PERT CHART 22

3 GANTT CHART 23

4 CONTEXT LEVEL DIAGRAM (‘0’ LEVEL


DFD

5 USE CASE REALIZATIONS 31

6 INTERACTION DIAGRAMS 32

7 DEPLOYMENT DIAGRAM 33
INTRODUCTION

1. Introduction
1.1. Background:
Amazon Technologies a private owned organization in the capital city of Andhra Pradesh, Hyderabad,
that in operation since 2005 works for managing all the anonymities to the citizens of Hyderabad.
The organization works for the following goals in brief:

1. Project Implementation

2. ERP Consultation

3. Project Customization

4. Outsourcing Manpower for PEO(Professional Enterprise Organization)

5. Software Asset Management

6. Process Goal Management

7. Talent Management

8. Payroll and Benefits Administration of any organization

For the given set of works that the organization has to do it has to conduct regular meetings of
officials at the various levels with teleconferencing etc

Keeping in the mind the past glory and the success of the organization Kushboo’s administration
never would like to compromise to delay of the information or unsuccessful processing of any event,
which may rise during the build of any project.
Method Typically Followed by Organization

For all the communication purposes the organization typically follows the mode of communicating on
the paper and pen sending all the necessary documents through internal courier and making the last
movement reminders to all the officials over the telephones and E-Mails.

By the cost analysis the organization found that the overheads for following this path makes a lot of
avoidable expenses that could be easily cut down.

Plan to cut down the expenses;


Looking at the success in the field of IT and the infrastructure, the company has decided to automate
the communication procedure by installing a local Intranet chat. This would avoid the unnecessary
use of Paper and Telephone calls. And these entities usually add to the cost overhead of the
organization.

With these set of tasks to be performed Kushboo’s organization, hence have decided to develop a
system that can make the administration of the organization better.

1.2. Objectives:

To be one of the best in the market in providing quality and reliable services in meeting the
employees satisfaction through the maximum utilization of the resources to generate profitability for
future enhancements.

With the growing cost factor and the decrease of the flow of cash in the world’s economy, The
Company Management have decided to build an internal tool, so that it could be cost efficient and
would provide the benefit of licenses.

This could also directly save the environment as the consumption of the papers and pens should be
minimal after the implementation of the project.

1.3 Purpose and Scope

1.3.1 Purpose:
Purpose of this project is to create a Chat Communicator which has a feature of deploying a
server, deploying a client, authorizing the client establishing a Client Server Communication using
TCP/IP Protocol, saving the chat logs.
1.3.2 Scope:
The Scope Includes:

• To develop Group communication Client and server software

• Allowing the Clients to Multicast their messages,

• Chat server program should listen to the incoming calls.

• To enable communication between the clients through different IP’s.

• The server should maintain a log of the communication made between the various clients.

SURVEY OF TECHNOLOGIES

Technical Information

2.1 TCP/IP Model Architecture:

The TCP/IP model is a description frame work for computer network protocols created in the 1970s
by DARPA, an agency of the United States Department of Defence. It evolved from ARPANET,
which was the world's first wide area network and a predecessor of the Internet. The TCP/IP Model is
sometimes called the Internet Reference Model or the DoD Model.

The TCP/IP model, or Internet Protocol Suite, describes a set of general design guidelines and
implementations of specific networking protocols to enable computers to communicate over a
network. TCP/IP provides end-to-end connectivity specifying how data should be formatted,
addressed, transmitted, routed and received at the destination. Protocols exist for a variety of different
types of communication services between computers.

TCP/IP is generally described as having four abstraction layers (RFC 1122). This layer architecture is
often compared with the seven-layer OSI Reference Model formalized after the TCP/IP specifications.

The TCP/IP model and related protocols are maintained by the Internet Engineering Task Force
(IETF).

Seven layer of OSI model


1. Physical Layer

2. Data link layer

3. Network layer

4. Transport Layer

5. Session Layer

6. Presentation layer

7. Application layer

Physical layer:
The Physical Layer is the first and lowest layer in the seven-layer OSI model of computer networking.
The Physical Layer comprises the basic hardware transmission technologies of a network. It is a
fundamental layer underlying the logical data structures of the higher level functions in a network.
The Physical Layer defines the means of transmitting raw bits rather than logical data packets over a
physical link connecting network nodes. The bit stream may be grouped into code words or symbols
and converted to a physical signal that is transmitted over a hardware transmission medium. The
Physical Layer provides an electrical, mechanical, and procedural interface to the transmission
medium

Data link Layer:


The Data Link Layer is Layer 2 of the seven-layer OSI model of computer networking. The Data Link
Layer is the protocol layer which transfers data between adjacent network nodes in a wide area
network or between nodes on the same local area network segment

The Data Link Layer provides the functional and procedural means to transfer data between network
entities and might provide the means to detect and possibly correct errors that may occur in the
Physical Layer. Examples of data link protocols are Ethernet for local area networks (multi-node), the
Point-to-Point Protocol (PPP), HDLC and ADCCP for point-to-point (dual-node) connections.

Network Layer:
The Network Layer is Layer 3 of the seven-layer OSI model of computer networking. The Network
Layer is responsible for end-to-end (source to destination) packet delivery including routing through
intermediate hosts, whereas the Data Link Layer is responsible for node-to-node (hop-to-hop) frame
delivery on the same link.

The Network Layer provides the functional and procedural means of transferring variable length data
sequences from a source to a destination host via one or more networks while maintaining the quality
of service and error control functions.
Transport Layer:
In computer networking, the Transport Layer is a group of methods and protocols within a layered
architecture of network components within which it is responsible for encapsulating application data
blocks into data units (datagram, segments) suitable for transfer to the network infrastructure for
transmission to the destination host, or managing the reverse transaction by abstracting network
datagram and delivering their payload to an application. Thus the protocols of the Transport Layer
establish a direct, virtual host-to-host communications transport medium for applications and
therefore also referred to as transport protocols.

Session Layer:
The Session Layer is Layer 5 of the seven-layer OSI model of computer networking. The Session
Layer provides the mechanism for opening, closing and managing a session between end-user
application processes, i.e. a semi-permanent dialogue. Communication sessions consist of requests
and responses that occur between applications. Session Layer services are commonly used in
application environments that make use of remote procedure calls (RPCs).

Presentation Layer:
The Presentation Layer is Layer 6 of the seven-layer OSI model of computer networking. The
Presentation Layer is responsible for the delivery and formatting of information to the application
layer for further processing or display. It relieves the application layer of concern regarding
syntactical differences in data representation within the end-user systems. Note: An example of a
presentation service would be the conversion of an EBCDIC-coded text file to an ASCII-coded file.

Application Layer:
Application Layer is a term used in categorizing protocols and methods in architectural models of
computer networking. Both the OSI model and the Internet Protocol Suite (TCP/IP) contain an
application layer.In TCP/IP, the Application Layer contains all protocols and methods that fall into
the realm of process-to-process communications via an Internet Protocol (IP) network using the
Transport Layer protocols to establish underlying host-to-host connections.
TCP/IP
Architectural Model
2.2 UDP Protocol:

The User Datagram Protocol (UDP) is one of the core members of the Internet Protocol Suite, the set
of network protocols used for the Internet. With UDP, computer applications can send messages, in
this case referred to as datagram, to other hosts on an Internet Protocol (IP) network without requiring
prior communications to set up special transmission channels or data paths. UDP is sometimes called
the Universal Datagram Protocol. The protocol was designed by David P. Reed in 1980 and formally
defined in RFC 768.

UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing
reliability, ordering, or data integrity. Thus, UDP provides an unreliable service and datagram may
arrive out of order, appear duplicated, or go missing without notice. UDP assumes that error checking
and correction is either not necessary or performed in the application, avoiding the overhead of such
processing at the network interface level. Time-sensitive applications often use UDP because
dropping packets is preferable to using delayed packets. If error correction facilities are needed at the
network interface level, an application may use the Transmission Control Protocol (TCP) or Stream
Control Transmission Protocol (SCTP) which are designed for this purpose.

UDP's stateless nature is also useful for servers that answer small queries from huge numbers of
clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all on local network) and
multicasting (send to all subscribers).

Common network applications that use UDP include: the Domain Name System (DNS), streaming
media applications such as IPTV, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP) and
many online games.

2.3 Java - J2EE Architecture


Java Platform, Standard Edition:

Java program falls into two categories, applications and applets.

An application is a program that can execute from any operating system prompt. Standalone
applications can either be windows-based applications or console applications. Windows-based
applications can have a graphical user interface. They use features that are supported by platforms like
Microsoft, Macintosh, Motif, and OS/2. Console applications are the character based application that
do not have a graphical user interface. A stand alone application uses the resources of a single
computer. Network applications can access objects that execute across many computers over a
network. Distributed applications can access objects that execute across many computers on a
network.

Applications are allowed to read from and write to the files on the local computer. Applications
establish network connections, access resources across a network, and launch applications over a
network.

A stand-alone application resides on the HDD of a local machine. When the application needs to be
executed, it is fetched from the HDD into the memory and executed.

2.4 J2EE Platform and Applications:


With features designed to expedite the process of developing distributed applications, the
J2EE platform offers several benefits:

• Simplified architecture and development


• Freedom of choice in servers, tools, and components
• Integration with existing information systems
• Scalability to meet demand variations
• Flexible security model

Simplified Architecture and Development:

The J2EE platform supports a simplified, component-based development model. Because it is based
on the Java programming language and the Java 2 Platform, Standard Edition (J2SE platform), this
tm

model offers "Write-Once-Run-AnywhereTM" portability, supported by any server product that


conforms to the J2EE standard.

The component-based J2EE development model can enhance application development


productivity in a number of ways:

• Maps easily to application functionality--Component-based application models map easily and


flexibly to the functionality desired from an application.

• Enables assembly- and deploy-time behaviors--Because of the high level of service


standardization, much of the code of a J2EE application can be generated automatically by tools,
with minimal developer intervention. In addition, components can expect standard services to be
available in the runtime environment and can dynamically connect to other components by means
of consistent interfaces. As a result, many application behaviours can be configured at application
assembly or deployment time, without recoding.

• Supports division of labor--Components help divides the labor of application development among
specific skill sets, enabling each member of a development team to focus on his or her ability. Web
page authors can create JSP templates, Java programming language coders can implement
application behaviour, domain experts can develop business logic, and application developers and
integrators can assemble and deploy applications. This division of labor also expedites application
maintenance. For example, the user interface is the most dynamic part of many applications,
particularly on the Web. With the J2EE platform, Web page authors can tweak the look and feel of
JSP pages without programmer intervention.
2.5 Project Management Stylus:
Defining project success before you start requires critical and conceptual thinking. A project can be
conceived as a measured chain of achievements and this chain is created by starting at the end of the
project. This last achievement in a project is what defines the success of the project. This
measurement is not just a deliverable and a due date; it is instead a strategic result that needs to be
defined with clear consultation with the stakeholders. Let's talk about what project management is
all about.

Initiation and Definition Phase: The problem is identified, available solutions are studied, potential
solutions determined and a project brief is created in this stage. A decision is made to outsource or
work on the project internally. As may be the case, the service provider and the team members are
then identified. The project scope defines the vision and the end-results of the project. A needs
analysis document will gather detail information like target audience, technology profiling, budget
and schedule, staffing and risks. A project scope or proposal document is then developed as a detailed
proposal for meeting project needs. team to work on the project. A project plan is then developed. It
Team Management: The project leader/manager aims to create an atmosphere of a cooperative and
effective team culture. Team management includes all the processes that are needed to identify and
secure an effective project team. Determining where the requisite staff can be obtained and then
identifying the roles and responsibilities of each team member, how they communicate with each
other and build the necessary rapport, undergo training if necessary, resolve conflicts and monitor
performance levels are necessary to ensure the effectiveness of the team.

Communication Management: Effective communication in a project between all the stakeholders and
the project team is imperative as it ensures that the stakeholders gain and maintain a clear
understanding of the status of project's progress. This could either be a weekly report on the status, on
the risks involved, the schedule and the budget status and can be in a documented format or handed
out or reported in a meeting. At Stylus, we hold information meetings every Monday where all the
projects are reported about and explained. This also ensures that the entire organization is aware of all
that happens on the projects and project-related activities within the organization.

Risk Management: The project plan usually contains a risk plan that describes strategies and methods
used to identify and avoid risks throughout the life cycle of the project. All kinds of risks are
identified here - business risks that are associated with the nature of the work done or the client and
the target environment, risks within the project and the team environment and finally technical risks
involved with the system or other aspects of the technology of the application.
Configuration Management: In any project, many versions and files are created during the project
and thus increasing the number of versions and components of the product. It is important to identify
and track these versions and document how any changes made to these documents will be handled
and reported. All project documentation; project hardware and software and project outputs are placed
under project management.

Quality Management: Evaluation and testing activities contribute to how the final deliverable in a
project adheres to relevant standards. Quality of a package or deliverable doesn't mean checking it at
the end and ensuring that it is bug free. It also means quality is tracked right through the project. A
quality management plan is developed at the beginning of the project and a quality check
representative is assigned to a project at the beginning of the project.

Project Time Management: Developing procedures to manage activities and the schedule of a project
involve giving a detailed schedule at the project definition stage. A work breakdown structure is
developed based on the proposal in the project scope document and agreed to in the project contract.

Cost Management: To ensure that the costs are maintained during the project, the project manager
with the help of the client requirements capture team proposes the budget and the resources involved
in the project at the beginning when the scope of the project is defined. These budgets and schedules
are reviewed at regular intervals, especially when deliverables are iteratively defined in a project.

The Project Brief is likely to contain:

• A statement of the teaching and learning problem.

• A summary of the intended outcomes of the package you are developing.

• A brief description of the selected potential solution.

• Reasons why the solution has been selected.

• A discussion of how you think this solution will actually work to solve the problem.

• A discussion of other available solutions, their strengths and weaknesses.

• A description of who will benefit from the solution and how.


An analysis of the views of these stakeholders.

2.6 Which Protocol Must Be Used ? TCP/IP or UDP!!


Each protocol has its own specifications, But we found that TCP/IP was much more feasible for us,
since it had noted advantages over UDP. Choosing the right transport protocol to use depends on the
type of data to be transferred. For information that needs reliability, sequence transmission and
data integrity — TCP is the transport protocol to use. For data that require real-time transmission
with low overhead and less processing — UDP is the right choice.
REQUIREMENTS AND ANALYSIS

3.1 Problem Definition:


We have to develop Group communication Client (Software) that would allow the users to multicast
their messages. The Chat server should be in a position to listen the incoming calls and should also
enable communication between Clients through different IP’s. That Chat Server should also maintain
a log of communication made between the various clients.

3.2 Requirements Specification:


Requirements for Group Chat Client:

1. This software will allow Clients to register with the Sever.

2. Only Authorized Clients attached through the Server could chat.

3. System will allow saving the log (chat). In other words the chat history could be saved on the
client system on the basis of the request raised by him.

4. The server will have the authorization to disconnect any client at any point of time.

5. System will generate popup message if the server chats with the client in the private mode.

Non requirements

1. System do not support the auto save feature of the client message, hence the
messages have to be saved explicitly one the chat is done.

3.3 Planning and Scheduling:

3.3.1 PERT CHART:

Program Evaluation Review Technique, PERT can be both a cost and a time
management system. PERT is organized by events and activities or tasks. PERT has several
advantages over bar charts and is likely to be used with more complex projects. One advantage of
PERT is that it is scheduling device that also shows graphically which tasks must be completed before
others are begun.

Also, by displaying the various task paths, PERT enables the calculation of a critical path.
Each path consists of combinations of tasks, which must be completed. PERT controls time and cost
during the project and also facilitates finding the right balance between completing a project on time
and completing it within the budget.

PERT CHART
31 MAR 15 APR 2009
2009

30 APR 2009
START I/O DESIGN
INTEGRATION
20 APR AND TESTING
2009

ANALYSIS

4 APR
2009
CODING FINISH
25 APR 2009
5 MAY 2009

WRITE
MANUAL 27 APR
2009

3.3.2 GANTT CHART (Bar Chart):

A Bar Chart is perhaps the simplest form of formal Library Management. The bar chart is also
known as Gantt chart. It is used almost exclusively for scheduling purposes and therefore controls
only the time of projects.

Gantt Charts are a project control technique that can be used for several purposes, including
scheduling, budgeting and resource planning. A Gantt chart is a Bar Chart, with each bar representing
an activity. The bars are drawn against a time line. The length of each bar is proportional to the length
of time planned for the activity.
The following steps describe the works that are carried out in the particular weeks.

 The problem has been identified and is discussed with in the group and the problem definition
is developed.

 The different types of software, hardware requirements and user requirements have been
identified and analyzed.

 The “software requirements document” has been developed.

 The interfaces have been designed manually and different modules are identified.

 The user interface components (swings) concept in java has been studies and discussed.

 The coding has been written to design the user interfaces.

 The data flow diagrams for the interfaces designed were prepared.

 The coding has been written to connect the database to the front end.

 The errors have been identified and corrected.


 Each individual module is tested individually to ensure that they produce correct output – unit
testing

 All the modules have been integrated and the integration testing performed on the system as a
whole.

The future enhancements have been made and the project is submitted with proper documentation
being evaluated by guide.

3.4 Software and Hardware Requirements:


3.1 Hardware Requirements:

The various hardware details required for the project are….

PROCESSOR : Intel Pentium IV or above

PROCESSOR Speed : 2.4 GHz or above

RAM : 512 MB or above

HDD : 40 GB or above

SCREEN : SVGA color

KEYBOARD : 101/104 soft touch keyboard

3.2 Software Requirement:


The various software requirements of this project are….

PLATFORM : Win NT, Windows XP

OPERATING System : Windows XP or above

Front End : Java

Miscellaneous : JDK1.6 version or more, NetBeans 5.0 IDE could be

Used as Java Native Client


3.5 Preliminary Product Description
The chat application under implementation by Amazon Technologies aims to reduce communication
costs while at the same time providing an effective and robust communication tool for employees of
the firm. The firm aims to use this tool to standardize communication from the present unorganized
fashion.

This section provides an overview of the Identification of requirement and objectives of the new
communication system and defines functions and operations of the application/system.

The initial phase involved gathering of requirements for the new application under development. At a
functional level, these can be summarized as

1. Providing an effective chat tool based on the client-server networking model.

2. Provision of two or more users communicating with each other through the application,
multiple users can communicate through text messages.

3. A log of all the communication done must be stored.

4. The server must be ‘intelligent’ to provide IP based authentication and ability for one-to-one
communication between clients.

5. Finally, Provision of functionality to broadcast and multicast the message to multiple/all


users.

At a business level, the requirements were to:

1. Robust communication medium to handle employee communication currently occurring


via paper/phone based communication.

2. Provide a record of all communication so as to keep track of old messages.

3. Fast, cost effective tool to cut down phone costs.

Thus to summarize, we can say the objectives of the new system are to:

Create a Chat Communicator which has a feature of deploying a server, deploying multiple clients,
authorizing the client to perform client-client and client-server networking and routing and lastly but
not the least saving the chat logs.

Now in the next section under this title, we attempt to describe the operational and functional aspects
in technical detail for our system.
We implement a Java based application because of features designed to enhance the process of
developing distributed applications, the J2EE platform offers several benefits such as Simplified
architecture, Freedom of choice in servers, tools, Ease of Integration, Scalability to meet demand
variations, Flexible security model etc.

On a micro level, the functionalities of the system were identified and implemented.

1. Chat server program listens for incoming calls from clients. Client running in any PC can
connect to the server if IP address of the server is known.

2. Server listens for messages from all the connected clients.

3. It broadcast the message from clients to all the clients connected to the server.

4. Chat client views the messages from all the clients and the server.

5. Client to Client interaction through IP based authentication is enabled by the server.

Our server will be a stand-alone program -- a single Java process running on its own machine. It won't
require any support software other than a Java virtual machine. And it won't require a Web server or
application server, although a Web server or application server will likely be used to serve the client
applet to the client. Our communications between client and server will pass through a Java object
called a Socket, called TCP/IP sockets. Sockets are not at all Java-specific; the term is taken directly
from the terminology of general IP (Internet Protocol) network programming.
All clients have to connect themselves to the server. The server should listen for client connection.

To interpret data flow, data should be encoded in a language understandable by the server and the
client. By using the same language for the client and the server, the sender is sure that his data sent are
well processed by the receiver. For example, a client can send an instruction (to the server) to transmit
some data to another.

3.6 Conceptual Models


Data Flow Diagram
A data-flow diagram (DFD) is a graphical representation of the "flow" of data through an information
system. A data-flow diagram can also be used for the visualization of data processing.

The DFD is designed to show how a system is divided into smaller portions and to highlight the flow
of data between those parts. Data-flow diagrams (DFDs) are one of the three essential perspectives of
the structured-systems analysis and design method. With a data-flow diagram, users are able to
visualize how the system will operate, what the system will accomplish, and how the system will be
implemented. Developing a data-flow diagram helps in identifying the transaction data in the data
model.

DFD approach:
1. The system designer makes "a context level DFD" or Level 0, which shows the "interaction" (data
flows) between "the system" (represented by one process) and "the system environment" (represented
by terminators).

2. The system is "decomposed in lower-level DFD (Level 1)" into a set of "processes, data stores, and
the data flows between these processes and data stores".

3. Each process is then decomposed into an "even-lower-level diagram containing its sub processes".

4. This approach "then continues on the subsequent sub processes", until a necessary and sufficient
level of detail is reached which is called the primitive process.

DFD is also a virtually designable diagram that technically or diagrammatically describes the inflow
and outflow of data or information that is provided by the external entity

Data flow diagram levels:


Context Level Diagram:

This level shows the overall context of the system and its operating environment and shows the whole
system as just one process.

Level 1 (High Level Diagram):


This level (level 1) shows all processes at the first level of numbering, data stores, external entities
and the data flows between them. The purpose of this level is to show the major high-level processes
of the system and their interrelation

Level 2 (Low Level Diagram)

This level is a decomposition of a process shown in a level-1 diagram, as such there should be a level-
2 diagram for each and every process shown in a level-1 diagram.

Context Level Diagram (‘0’ Level DFD)

Client 1 sends a message Client 2 receives the message

Client 1 Server Client 2

Client 1 receives the reply Client 2 sends the reply

SYSTEM DESIGN
4.1 Basic Modules

First step is to identifying all the features that needs to be implemented in the software. The
requirements are a good guide in identifying the features. According to the requirements specification,
we need to develop the following features in the system.

The chat application has to have feature of a server, clients able to connect to it, server able to
accept/reject clients, client-client communication once both are allowed by server, broadcasting by
server to all the active clients on the network. Finally, there needs to be a memory space to store all
the messages in the log. This saving has to be done at the client system and also auto-save is not an
option in our system.

Using our Chat application, one can:

1. Communicate with each other.

2. Broadcast to all the active users an important message

3. Obtain a record of all communication through the log.

4.2 Procedural Design

UML forms one of the most essential tools effectively used by almost all the software development
organizations. The model’s which remains outcome of UML guides the coders through rest of the
software development task. It has been estimated that behind every successful software product, 50%
of the share is taken away by expect human visualization and the models drawn out of it. Hence,
UML is not just drawing sketches; it is a notion to drop down the complex software systems to its
lowest levels using human oriented languages.

Identification of actors involved in the system

Actors hold a significant role in every human interactive application. In our application the probable
actors can be

- User/client
- Server

As usual, every actor in UML is represented using a stick diagram.

Determining the probable use cases of the system


Use Case diagram narrating the consequence of the chat application:

SNo Use Case Description

1 Login Client provides Server IP, port details to server

2 Permission Server verifies client request, checks for validity of sent


data and accepts/discards client.

3 Chat Permission Two active clients request server permission to chat.


Server accepts or rejects the requests.
4 Chat Two clients given permission by server talk to each
other.

5 Save chat When closing of application by client, option to save


chat on local system is given to user to save his
communication.

6 Broadcasting Messages Server decides to send a common message to all active


clients.
Use Case Realizations

Login
Client 1 Client 2

Server verifies client


request, checks for
validity of sent data

Permission

Two active clients


request server
permission to chat.
Chat Permission

Two clients given


permission by server

Chat

When closing of
application by client,
option to save chat on
Save Chat

Server decides to send


a common message to
all active clients. Broadcasting Messages
Server
Interaction Diagrams

Client 1 Login Server Client 2 Logs Logout

Enter IP Address and Port Number

Checks for Permission

Permission Granted

Enter IP Address and Port Number

Checks for Permission

Permission Granted

Client 1 request for permission to chat with Client 2 and once granted , can chat with client 2

Server can Broadcast the message to all the clients on the Server

Client 1 can save the chat

Client 2 can save the chat

Client 1 logouts the system when finished with the chat

Client 2 logouts the system when finished with the chat


Deployment Diagram
Work Station

Client 3
Client 1 Client 2

Logs to Save
Server the Chat

4.3 Test Cases Design

Following is a template for the RS document. Some example requirements are entered in to it to show
how to use the template. This would help in validating the system during testing.

No. Requirement Essential Description of the Remarks


or Requirement
Desirable

RS1 The client should Essential Client asks for The server’s IP, port details
enable login to permission by are known to all clients on
network contacting server the network
on and providing it
IP, port details

RS2 The server must Essential The server verifies The discarded client cannot
accept or discard the the details access the network to
client provided by client communicate with other
and process them clients
to accept/reject
client
RS3 Client-client chat Essential A client provides Main functionality of our
must be enabled details of other application
client it wants to
chat with to the
server which will
grant access

RS4 Upon closing of Essential Once client chats


communication, save with a client,
option must be option must be
provided given to user to
save the
conversation
locally on the
client system

RS5 Server broadcasting Essential Server scans the


messages to all active network for all
clients active clients and --
sends a common
message to all of
them

Implementation & Testing

5.1 Implementations Approaches


The coding of the entire application has been done in Java. It provides an effective platform to code
and implement a chat application. Also beneficial are its features of scalability, reliability and
security. Thus leveraging these inbuilt features, it was decided to use the Java platform.

Java is one of the first programming languages to consider security as part of its design. The Java
language, compiler, interpreter, and runtime environment were each developed with security in mind.
The compiler, interpreter, and Java-compatible browsers all contain several levels of security
measures that are designed to reduce the risk of security compromise, loss of data and program
integrity, and damage to system users.

Java is portable, multithreaded, architecture neutral and robust thus making it a preferable language
for our application.

5.2 Coding Details and Code Efficiency


Chat Main.java
import java.net.InetAddress;

import java.net.UnknownHostException;

import javax.swing.JDialog;

import javax.swing.JFrame;

import org.jouvieje.network.ClientConnection;

import org.jouvieje.network.ServerConnection;

import org.jouvieje.network.Chat.*;

import org.jouvieje.network.Chat.protocol.ChatServerLink;

public class ChatMain

public static void main(String[] args)

JDialog.setDefaultLookAndFeelDecorated(true);

JFrame.setDefaultLookAndFeelDecorated(true);

if(args.length == 0)
{

new IntroFrame().setVisible(true);

else if(args.length == 1)

//creates the two connections

ServerConnection<ChatServerLink> server = null;

try

server = new
ServerConnection<ChatServerLink>(Integer.parseInt(args[0]));

catch(NumberFormatException e)

System.out.println("Invalide use of ChatMain :");

System.out.println("/tChatMain <CommunicationPort>");

System.exit(1);

new Server(server).setVisible(true);

else if(args.length == 3)

InetAddress IP = null;

try

IP = InetAddress.getByName(args[1]);

catch(UnknownHostException e)
{

e.printStackTrace();

System.exit(1);

ClientConnection client = null;

try

client = new ClientConnection(IP, Integer.parseInt(args[0]));

catch(NumberFormatException e1)

System.out.println("Invalide use of ChatMain :");

System.out.println("/tChatMain <CommunicationPort> <IP>


<YourPseudo>");

System.exit(1);

new Client(client, args[2]).setVisible(true);

----------------------------------------------------------------------------------------------------------------

About me.Java
package org.jouvieje.tools;

import java.awt.*;

import java.awt.event.*;

import java.net.MalformedURLException;

import java.net.URL;

import javax.swing.*;

import javax.swing.border.TitledBorder;
import org.jouvieje.network.HtmlViewer.HtmlViewerDialog;

public class AboutMeDialog extends JDialog

private final static int OFFSET_WITHOUT_HELP = -56;

private final boolean animated;

private final String info;

private final String help;

private final int yOffset;

private JPanel jContentPane = null;

private JLabel jPicture = null;

private JLabel jInfo = null;

private JLabel jAuteur = null;

private JLabel jEmail = null;

private JLabel jSite = null;

private JLabel jSite1 = null;

private JLabel jSite2 = null;

private JPanel jHelp = null;

private JLabel jHelpLabel = null;

public AboutMeDialog(boolean animated, String infoApp, String[] help)

super();

this.animated = animated;

this.info = infoApp;
if(help != null)

this.yOffset = help.length*13;

else

this.yOffset = OFFSET_WITHOUT_HELP;

this.help = toHelpText(help);

initialize();

public AboutMeDialog(Frame owner, boolean modal, boolean animated, String


infoApp, String[] help)

super(owner, modal);

this.animated = animated;

this.info = infoApp;

if(help != null)

this.yOffset = help.length*13;

else

this.yOffset = OFFSET_WITHOUT_HELP;

this.help = toHelpText(help);

initialize();

public AboutMeDialog(Dialog owner, boolean modal, boolean animated, String


infoApp, String[] help)

super(owner, modal);

this.animated = animated;

this.info = infoApp;

if(help != null)

this.yOffset = help.length*13;

else
this.yOffset = OFFSET_WITHOUT_HELP;

this.help = toHelpText(help);

initialize();

private void initialize()

this.setContentPane(getJContentPane());

this.setSize(352, 349+yOffset);

this.setTitle("About Me");

this.setLocationRelativeTo(null);

this.setResizable(false);

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

private JPanel getJContentPane()

if(jContentPane == null)

jContentPane = new JPanel();

jContentPane.setLayout(null);

jContentPane.setBackground(Color.black);

jContentPane.setForeground(Color.yellow);

jContentPane.add(getJPicture(), null);

jContentPane.add(getJInfo(), null);

jContentPane.add(getJAuteur(), null);

jContentPane.add(getJEmail(), null);

jContentPane.add(getJSite(), null);

jContentPane.add(getJSite1(), null);
jContentPane.add(getJSite2(), null);

if(help != null && !help.equals(""))

jContentPane.add(getJHelp(), null);

return jContentPane;

private JLabel getJPicture()

if(jPicture == null)

jPicture = new JLabel();

jPicture.setHorizontalAlignment(SwingConstants.LEFT);

if(animated)

jPicture.setIcon(new
ImageIcon(getClass().getResource("/Data/Picture/Auteur.gif")));

else

jPicture.setIcon(new
ImageIcon(getClass().getResource("/Data/Picture/Auteur.jpg")));

jPicture.setBounds(0, 0, 346, 152);

return jPicture;

private JLabel getJInfo()

if(jInfo == null)

jInfo = new JLabel();


jInfo.setBackground(new Color(0, 0, 0));

jInfo.setForeground(new Color(255, 255, 0));

jInfo.setHorizontalAlignment(SwingConstants.CENTER);

jInfo.setText(info);

jInfo.setBounds(0, 155, 346, 16);

return jInfo;

private JLabel getJAuteur()

if(jAuteur == null)

jAuteur = new JLabel();

jAuteur.setBackground(new Color(0, 0, 0));

jAuteur.setForeground(new Color(255, 255, 0));

jAuteur.setHorizontalAlignment(SwingConstants.CENTER);

jAuteur.setText("Author : Jouvieje");

jAuteur.setBounds(0, 174, 346, 16);

return jAuteur;

private JLabel getJEmail()

if(jEmail == null)

jEmail = new JLabel();

jEmail.setBackground(new Color(0, 0, 0));

jEmail.setForeground(new Color(255, 255, 0));


jEmail.setHorizontalAlignment(SwingConstants.CENTER);

jEmail.setText("<HTML>E-mail: <FONT COLOR=\"#639ACE\"><A


HREF=\"mailto:manish.bvc@gmail.com\">manish.bvc@gmail.com</A></FONT></HTML
>");

jEmail.setBounds(0, 193, 346, 16);

return jEmail;

private JLabel getJSite()

if(jSite == null)

jSite = new JLabel();

jSite.setText("Web site :");

jSite.setBackground(Color.black);

jSite.setForeground(Color.yellow);

jSite.setHorizontalAlignment(SwingConstants.CENTER);

jSite.setBounds(25, 212, 60, 16);

return jSite;

private JLabel getJSite1()

if(jSite1 == null)

jSite1 = new JLabel();

jSite1.setText("<html><font color=\"#639ACE\"><a
href=\"http://manish.mitra.fr/\">http://manish.mitra.fr/</a></font></html>");

jSite1.setBounds(91, 212, 222, 16);


jSite1.setBackground(Color.black);

jSite1.setForeground(Color.yellow);

jSite1.setHorizontalAlignment(SwingConstants.LEFT);

jSite1.setCursor(new Cursor(Cursor.HAND_CURSOR));

jSite1.addMouseListener(new MouseAdapter() {

URL link = null;

String urlAsString = "http://abc.chatcompany.php";

private URL getLink() {

if(link == null) {

try {

link = new URL(urlAsString);

catch(MalformedURLException e) {

e.printStackTrace();

return link;

public void mouseClicked(MouseEvent e) {

openURL(getLink(), urlAsString);

});

return jSite1;

private JLabel getJSite2()

if(jSite2 == null)
{

jSite2 = new JLabel();

jSite2.setText("<html> <font color=\"#639ACE\"><a


href=\"http://google.co.uk/~mamitra/\">http://google.co.uk/~mamitra/</a></font></html>");

jSite2.setBackground(Color.black);

jSite2.setForeground(Color.yellow);

jSite2.setHorizontalAlignment(SwingConstants.LEFT);

jSite2.setBounds(91, 231, 234, 16);

jSite2.setCursor(new Cursor(Cursor.HAND_CURSOR));

jSite2.addMouseListener(new MouseAdapter() {

URL link = null;

String urlAsString =
"http://google.co.uk/~mamitra/manish/manish/index.php";

private URL getLink() {

if(link == null) {

try {

link = new URL(urlAsString);

catch(MalformedURLException e) {

e.printStackTrace();

return link;

public void mouseClicked(MouseEvent e) {

openURL(getLink(), urlAsString);

});

}
return jSite2;

private JPanel getJHelp()

if(jHelp == null)

GridBagConstraints gridBagConstraints1 = new GridBagConstraints();

gridBagConstraints1.fill = GridBagConstraints.BOTH;

gridBagConstraints1.gridx = 1;

gridBagConstraints1.gridy = 1;

gridBagConstraints1.weightx = 1.0D;

gridBagConstraints1.weighty = 1.0D;

gridBagConstraints1.insets = new Insets(0, 10, 8, 10);

jHelp = new JPanel();

jHelp.setLayout(new GridBagLayout());

TitledBorder ivjTitledBorder =
BorderFactory.createTitledBorder(null , "Menu d\'aide" ,
TitledBorder.DEFAULT_JUSTIFICATION , TitledBorder.DEFAULT_POSITION , new
Font("Dialog", Font.BOLD, 13) , Color.yellow);

ivjTitledBorder.setTitle("Help Menu");

jHelp.setBorder(ivjTitledBorder);

jHelp.setBackground(new Color(0, 0, 0));

jHelp.setForeground(new Color(255, 255, 0));

jHelp.setBounds(30, 251, 286, 50+yOffset);

jHelp.add(getJHelpLabel(), gridBagConstraints1);

return jHelp;

private JLabel getJHelpLabel()


{

if(jHelpLabel == null)

jHelpLabel = new JLabel();

jHelpLabel.setText(help);

jHelpLabel.setVerticalAlignment(SwingConstants.TOP);

jHelpLabel.setBackground(new Color(0, 0, 0));

jHelpLabel.setForeground(new Color(255, 255, 0));

return jHelpLabel;

private String toHelpText(String[] helps)

if(helps == null)

return "";

String s = "<html><body>";

for(int i = 0; i <= helps.length-1; i++)

s += helps[i]+"<br>";

s += "</body></html>";

return s;

/**

* Open an URL in a new Window

* @param link

*/
private void openURL(URL link, String urlAsString)

new HtmlViewerDialog(this, isModal(), link).setVisible(true);

Client Connection.java
package org.jouvieje.network;

import java.io.*;

import java.net.*;

/**

* Represents a connection of a Client with a server.

*/

public class ClientConnection implements Connectable<Socket>

/** Socket on the client side linked to the server socket */

protected Socket socket = null;

/** Communication protocol */

private Protocol protocol = null;

/** Server (host) IP */

private final InetAddress hostIP;

/** Communication port of the server */

private final int hostPort;

protected ClientConnection()

this.hostIP = null;

this.hostPort = -1;
}

/**

* @param hostIP IP of the server to communicate with him

* @param hostPort communication port used for the connection

*/

public ClientConnection(InetAddress hostIP, int hostPort)

this.hostIP = hostIP;

this.hostPort = hostPort;

/**

* Open the connection to the server and creates a socket to communicates with him.

* @return true if the connection is made

*/

public boolean connect()

try

/*

* Creates the Socket

*/

socket = new Socket(hostIP, hostPort);

return socket.isConnected();

catch(IOException e)

{
e.printStackTrace();

return false;

/**

* @return the socket used to communicates with the server

*/

public Socket getSocket()

return socket;

/**

* Disconnect to the server

* @return true if the client is disconnected without errors

*/

public boolean disconnect()

if(!isConnected())

return true;

try

if(getSocket() != null)

getSocket().close();

catch(IOException e)
{

e.printStackTrace();

return !isConnected();

/**

* @return true if the socket was connected and not closed.

*/

public boolean isConnected()

if(getSocket() != null)

return getSocket().isConnected() && !getSocket().isClosed();


//is connected and is opened

return false;

/**

* Send datas

* @param data data to send

* @return bytes sended, -1 if an IOException occures

*/

public int send(String data) throws IOException

OutputStreamWriter out = new


OutputStreamWriter(getSocket().getOutputStream());

out.write(data);

out.flush();

return data.length();
}

/**

* Send datas

* @param data data to send

* @return bytes sended, -1 if an IOException occures

*/

public int send(byte[] data) throws IOException

OutputStream out = getSocket().getOutputStream();

out.write(data, 0, data.length);

out.flush();

return data.length;

/**

* Equivalent to <code>send(is, 512*1024)</code>

*/

public int send(InputStream is) throws IOException

return send(is, 512*1024); //512 kb buffer

/**

* Send datas

* @param data data to send

* @param buffSize size a the sending buffer

* @return bytes sended, -1 if an IOException occures

*/
public int send(InputStream is, int buffSize) throws IOException

OutputStream out = getSocket().getOutputStream();

int sent = 0;

byte[] datas = new byte[buffSize];

while(is.available() > 0)

int readed = is.read(datas);

out.write(datas, 0, readed);

sent += readed;

out.flush();

return sent;

/**

* Send datas

* @param data data to send

* @param buffer reading buffer

* @return bytes sended, -1 if an IOException occures

*/

public int send(InputStream is, byte[] buffer) throws IOException

OutputStream out = getSocket().getOutputStream();

int sent = 0;

while(is.available() > 0)

int readed = is.read(buffer);

out.write(buffer, 0, readed);
sent += readed;

out.flush();

return sent;

/**

* @return nb byte input

*/

public int hasInput()

if(getSocket() == null)

return -1;

try

return getSocket().getInputStream().available();

catch(IOException e)

return -1;

/**

* Read datas received

* @return data received

*/

public byte[] readInput() throws IOException

{
if(getSocket() == null)

new IOException();

//Don't use a BufferedInputStream, by experience I found some problems

InputStream in = getSocket().getInputStream();

if(in.available() > 0)

byte[] input = new byte[in.available()]; //TODO Not the


best way if in.available is big

int reads = in.read(input, 0, input.length);

if(reads < input.length) //Just to be sure, not necessary I think

byte[] input_ = new byte[reads];

System.arraycopy(input, 0, input_, 0, reads);

input = input_;

return input;

return null;

public void checkInput() throws IOException

if(getProtocol() == null)

return;

if(getSocket() != null)

InputStream in = getSocket().getInputStream();

if(in.available() > 0)

{
//There is some problem synchronizing in few case when using
JOptionPane (blocking) ...

synchronized(getProtocol())

//Process input if protocol exist

getProtocol().processInput(in);

/**

* @return the communication protocol used

*/

public Protocol getProtocol()

return protocol;

/**

* @param protocol communication protocol used

*/

public void setProtocol(Protocol protocol)

this.protocol = protocol;

/**

* @return your IP

*/
public InetAddress getLocalIP()

if(getSocket() != null)

return getSocket().getLocalAddress();

return null;

/**

* @return the IP of the server

*/

public InetAddress getRemoteIP()

if(isConnected())

return getSocket().getInetAddress();

return hostIP;

/**

* @return your communication port used (-1 if not yet connected)

*/

public int getLocalPort()

if(getSocket() != null)

return getSocket().getLocalPort();

return -1;

/**
* @return the communication port of the server

*/

public int getRemotePort()

if(getSocket() != null)

return getSocket().getPort();

return hostPort;

/**

* @return true if the user is a server

*/

public boolean isServer()

return false;

Connectable.java
package org.jouvieje.network;

import java.net.InetAddress;

/**

* Represent a Client/Server connection.

*/

public interface Connectable<E>

/**

* Open the connection

* @return -1 on failure

*/
public boolean connect();

/**

* Close the connection

* @return true on success

*/

public boolean disconnect();

/**

* @return true if the user is connected

*/

public boolean isConnected();

/**

* Socket used for the communication.

* @return the socket used to communicates

*/

public E getSocket();

/**

* @return the IP of the client

*/

public InetAddress getLocalIP();

/**

* @return the IP of the server

*/

public InetAddress getRemoteIP();


/**

* @return the communication port of the client

*/

public int getLocalPort();

/**

* @return the communication port of the server

*/

public int getRemotePort();

/**

* @return true if it is a server

*/

public boolean isServer();

}\

Protocol.java

package org.jouvieje.network;

import java.io.InputStream;

public interface Protocol

/**

* Process inputs, decode the data received to do all needed things

* @param datas datas received

*/

public void processInput(InputStream datas);


}

Server Connection.java
package org.jouvieje.network;

import java.io.*;

import java.net.*;

import java.util.Vector;

/**

* Represents a connection of a server with one or more clients.

*/

public class ServerConnection<E extends ServerLink> implements


Connectable<ServerSocket>

/** Server socket for listening clients */

private ServerSocket serverSocket = null;

/** Communication port of the server to listen request of access */

private int port;

/** List of connection with a client */

private Vector<E> clients = null;

/** ServerLinkCreator used to creates ServerLink objects */

private ServerLinkCreator<E> serverLinkCreator = null;

/**

* @param port communication port on the server to check access of clients.

*/

public ServerConnection(int port)

{
this.port = port;

clients = new Vector<E>();

/**

* Create the ServerSocket and bound it to the communication port.<BR>

* @return false if the connection fails

*/

public boolean connect()

try

/*

* Creates a ServerSocket

* This is used to open a communication port to clients

*/

serverSocket = new ServerSocket(port);

return true;

catch(Exception e)

e.printStackTrace();

serverSocket = null;

return false;

/**
* Listen on the port for a client connection request.<BR>

* The method blocks until a connection is made.

*/

public E acceptConnection()

try

//Accept a client

Socket socket = serverSocket.accept();

return addLink(socket);

catch(IOException e)

return null;

/**

* @return the ServerSocket of the server

*/

public ServerSocket getSocket()

return serverSocket;

private void closeServerSocket() throws IOException

if(serverSocket != null)

{
serverSocket.close();

serverSocket = null;

/**

* Add a client at the end of the ServerLink list

* @param socket to add

*/

private E addLink(Socket socket)

if(getServerLinkCreator() == null)

throw new RuntimeException("ServerLinkCreator = null");

E client = null;

try

client = getServerLinkCreator().create(socket); //Custom


creator

catch(Exception e)

e.printStackTrace();

client = null;

return null;

return clients.add(client) ? client : null;

}
/**

* Return a list of links with clients

*/

public Vector<E> getLinks()

return clients;

/**

* @return the link with the client in the index of the list.

* @deprecated

*/

public E getLink(int index)

synchronized(clients)

if(index >= 0 && index < clients.size())

return clients.get(index);

return null;

/**

* @return the number of clients connected

*/

public int getLinkCount()

return clients.size();
}

/**

* Close the connection with the client connected to the link.

* @return false if fail

*/

public boolean disconnectLink(E link)

if(link.disconnect())

return clients.remove(link);

return false;

/**

* Close the connection with all clients.

* @return true if the server closed without errors

*/

public void disconnectAllLink()

synchronized(clients)

//Close all connections

for(int i = 0; i < getLinkCount(); i++)

getLink(i).disconnect();

//Remove all client links from the list and create a new empty one

clients.clear();

clients = new Vector<E>();


}

/**

* Close the server

* @return true if the server closed without errors

*/

public boolean disconnect()

if(!isConnected())

return true;

//Disconnect all clients

disconnectAllLink();

try

//Close server

closeServerSocket();

return true;

catch(Exception e)

e.printStackTrace();

if(serverSocket != null && serverSocket.isClosed())

serverSocket = null;

return false;

}
/**

* @return true if the client is connected on the server

*/

public boolean isConnected()

if(serverSocket != null)

return !serverSocket.isClosed();

return false;

/**

* @return the ServerLinkCreator used to creates ServerLink when a client connects


him to the server

*/

public ServerLinkCreator<E> getServerLinkCreator()

return serverLinkCreator;

/**

* ServerLinkCreator used to creates ServerLink when a client connects him to the


server.

* @param linkCreator set null to use the default ServerLinkCreator.

*/

public void setServerLinkCreator(ServerLinkCreator<E> linkCreator)

this.serverLinkCreator = linkCreator;

}
/**

* @return null

*/

public InetAddress getRemoteIP()

return null;

/**

* @return IP of the server if connected

*/

public InetAddress getLocalIP()

if(isConnected())

return getSocket().getInetAddress();

return null;

/**

* @return -1

*/

public int getRemotePort()

return -1;

/**

* @return communication port listenned by the server

*/

public int getLocalPort()


{

if(getSocket() != null)

return getSocket().getLocalPort();

return port;

/**

* @return true if it is the server

*/

public boolean isServer()

return true;

Serverlink.Java

package org.jouvieje.network;

import java.io.IOException;

import java.net.Socket;

/**

* A ServerLink is a connection of the server to a client

*/

public class ServerLink extends ClientConnection implements


ServerLinkCreator<ServerLink>

public ServerLink create(Socket socket) throws IOException

return new ServerLink(socket);


}

/**

* @param socket socket already connected

*/

public ServerLink(Socket socket) throws IOException

this.socket = socket;

/**

* A ClientLink can't connects him becuse he's already connected.

* @return always false

*/

public boolean connect()

return true;

/**

* @return true if it is the server

*/

public boolean isServer()

return true;

}
ServerLinkCreator.java
package org.jouvieje.network;

import java.io.IOException;

import java.net.Socket;

public interface ServerLinkCreator<E extends ServerLink>

public E create(Socket socket) throws IOException;

ChatFrame.java

package org.jouvieje.network.Chat;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import javax.swing.*;

import javax.swing.filechooser.FileFilter;

import javax.swing.text.html.HTMLDocument;

import javax.swing.text.html.HTMLEditorKit;

import org.jouvieje.network.Chat.protocol.ProtocolEnums;

import org.jouvieje.network.parser.html.HtmlString;

import org.jouvieje.tools.AboutMeDialog;
/**

* Defines the common part of the client and the server frame.<BR>

* ClientFrame and ServerFrame extends this class.

*/

public abstract class ChatFrame<E> extends JFrame implements ProtocolEnums

public static boolean DEBUG_MODE = true;

protected final E user;

protected final String pseudo;

private JPanel jContentPane = null;

private JPanel jPanelTop = null;

private JLabel jInfoL = null;

private JLabel jPeusoL = null;

private JComboBox jPseudos = null;

private JSplitPane jSplit = null;

private JPanel jPanelSend = null;

private JLabel jInfoSend = null;

private JScrollPane jScrollSend = null;

private JTextPane jTextSend = null;

private JPanel jPanelSendButtons = null;

private JButton jButtonSend = null;

private JPanel jPanelReceive = null;

private JLabel jInfoReceive = null;

private JScrollPane jScrollReceive = null;

private JTextPane jTextReceive = null;

private JButton jButtonClear = null;


private JButton jButtonConnect = null;

private JMenuBar jJMenuBar = null;

private JMenu jMenuAbout = null;

private JMenuItem jMenuAboutDialog = null;

private JPanel jPanelButtonsReceived = null;

private JButton jButtonSave = null;

private JFileChooser jFileSaver = null;

protected ChatFrame(E user, String pseudo)

this.user = user;

this.pseudo = pseudo;

protected JPanel getJContentPane()

if(jContentPane == null)

jContentPane = new JPanel();

jContentPane.setLayout(new BorderLayout());

jContentPane.add(getJPanelTop(), BorderLayout.NORTH);

jContentPane.add(getJSplit(), BorderLayout.CENTER);

jContentPane.add(getJButtonConnect(), BorderLayout.SOUTH);

//Finishing the initialization

initializeEnd();

//Attach the events declared in an extended class

attachEvents();

}
return jContentPane;

protected JPanel getJPanelTop()

if(jPanelTop == null)

jPanelTop = new JPanel();

jPanelTop.setLayout(new BorderLayout());

jPanelTop.add(getJInfoL(), BorderLayout.NORTH);

jPanelTop.add(getJPeusoL(), BorderLayout.WEST);

jPanelTop.add(getJPseudos(), BorderLayout.CENTER);

return jPanelTop;

protected JLabel getJInfoL()

if(jInfoL == null)

jInfoL = new JLabel();

return jInfoL;

protected JLabel getJPeusoL()

if(jPeusoL == null)

jPeusoL = new JLabel();

jPeusoL.setText("You communicates with : ");


}

return jPeusoL;

protected JComboBox getJPseudos()

if(jPseudos == null)

jPseudos = new JComboBox();

jPseudos.setEnabled(false);

jPseudos.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

refreshInfo();

});

return jPseudos;

protected JSplitPane getJSplit()

if(jSplit == null)

jSplit = new JSplitPane();

jSplit.setOneTouchExpandable(true);

jSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);

jSplit.setLeftComponent(getJPanelSend());

jSplit.setRightComponent(getJPanelReceive());

jSplit.setDividerSize(8);

jSplit.setDividerLocation(getSize().width/2);
jSplit.setResizeWeight(0.5);

return jSplit;

protected JPanel getJPanelSend()

if(jPanelSend == null)

jPanelSend = new JPanel();

jPanelSend.setLayout(new BorderLayout());

jPanelSend.add(getJInfoSend(), BorderLayout.NORTH);

jPanelSend.add(getJScrollSend(), BorderLayout.CENTER);

jPanelSend.add(getJPanelSendButtons(), BorderLayout.SOUTH);

return jPanelSend;

protected JLabel getJInfoSend()

if(jInfoSend == null)

jInfoSend = new JLabel();

jInfoSend.setHorizontalAlignment(SwingConstants.CENTER);

return jInfoSend;

protected JScrollPane getJScrollSend()

if(jScrollSend == null)
{

jScrollSend = new JScrollPane(getJTextSend());

jScrollSend.setViewportView(getJTextSend());

return jScrollSend;

protected JTextPane getJTextSend()

if(jTextSend == null)

jTextSend = new JTextPane();

return jTextSend;

protected JPanel getJPanelSendButtons()

if(jPanelSendButtons == null)

jPanelSendButtons = new JPanel();

jPanelSendButtons.setLayout(new BorderLayout());

jPanelSendButtons.add(getJButtonSend(), BorderLayout.CENTER);

return jPanelSendButtons;

protected JButton getJButtonSend()

if(jButtonSend == null)

{
jButtonSend = new JButton();

jButtonSend.setText("Send");

jButtonSend.setEnabled(false);

return jButtonSend;

protected JPanel getJPanelReceive()

if(jPanelReceive == null)

jPanelReceive = new JPanel();

jPanelReceive.setLayout(new BorderLayout());

jPanelReceive.add(getJInfoReceive(), BorderLayout.NORTH);

jPanelReceive.add(getJScrollReceive(), BorderLayout.CENTER);

jPanelReceive.add(getJPanelButtonsReceived(),
java.awt.BorderLayout.SOUTH);

return jPanelReceive;

protected JLabel getJInfoReceive()

if(jInfoReceive == null)

jInfoReceive = new JLabel();

jInfoReceive.setHorizontalAlignment(SwingConstants.CENTER);

return jInfoReceive;

}
protected JScrollPane getJScrollReceive()

if(jScrollReceive == null)

jScrollReceive = new JScrollPane(getJTextReceive());

return jScrollReceive;

protected JTextPane getJTextReceive()

if(jTextReceive == null)

jTextReceive = new JTextPane();

jTextReceive.setDocument(new HTMLDocument());

jTextReceive.setEditorKit(new HTMLEditorKit());

jTextReceive.setText(new HtmlString().getHtmlCode());

jTextReceive.setEditable(false);

return jTextReceive;

private JPanel getJPanelButtonsReceived()

if(jPanelButtonsReceived == null)

jPanelButtonsReceived = new JPanel();

jPanelButtonsReceived.setLayout(new BorderLayout());

jPanelButtonsReceived.add(getJButtonClear(),
BorderLayout.CENTER);
jPanelButtonsReceived.add(getJButtonSave(),
java.awt.BorderLayout.EAST);

return jPanelButtonsReceived;

protected JButton getJButtonClear()

if(jButtonClear == null)

jButtonClear = new JButton();

jButtonClear.setText("Clear messages");

jButtonClear.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

getJTextReceive().setText(new
HtmlString().getHtmlCode());

});

return jButtonClear;

private JButton getJButtonSave()

if(jButtonSave == null)

jButtonSave = new JButton();

jButtonSave.setText("Save history");

jButtonSave.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)


{

int choice =
getJFileSaver().showSaveDialog(ChatFrame.this);

if(choice == JFileChooser.APPROVE_OPTION)

File file = getJFileSaver().getSelectedFile();

try

BufferedWriter br = new
BufferedWriter(new FileWriter(file));

HtmlString html = new


HtmlString(getJTextReceive().getText());

String bottomPage = "<P>File generated


by : TCP Client/Server Chat<BR>"+

"Author : Manish Mitra<BR>"+

"E-mail : <A
HREF=\"mailto:manish.mitra@oracle.com\">manish.mitra@oracle.com</A><BR>"+

"Site : <A
HREF=\"http://google.co.uk/~mamitra/\">http://google.co.uk/~mamitra/</A><BR>"+

"&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;&nbsp;&nbsp;"+

"<A
HREF=\"http://manish.mitra.fr/\">http://manish.mitra.fr/</A></P>";

html.insert(bottomPage);

br.write(html.getHtmlCode());

br.close();

catch(IOException e1)

JOptionPane.showMessageDialog(ChatFrame.this, "Fail to save the history");

return;
}

JOptionPane.showMessageDialog(ChatFrame.this, "History sucessfully saved in


"+file.getName());

});

return jButtonSave;

private JFileChooser getJFileSaver()

if(jFileSaver == null)

jFileSaver = new JFileChooser();

jFileSaver.setDialogTitle("Saving the history");

jFileSaver.setMultiSelectionEnabled(false);

jFileSaver.setFileFilter(new FileFilter() {

public boolean accept(File f)

return f.getName().toLowerCase().endsWith("html") ||

f.getName().toLowerCase().endsWith("htm") ||

f.isDirectory();

public String getDescription()

return "HTML file";

});
}

return jFileSaver;

protected JButton getJButtonConnect()

if(jButtonConnect == null)

jButtonConnect = new JButton("Connect");

return jButtonConnect;

protected JMenuBar getJJMenuBar()

if(jJMenuBar == null)

jJMenuBar = new JMenuBar();

jJMenuBar.add(getJMenuActions());

jJMenuBar.add(getJMenuAbout());

return jJMenuBar;

protected JMenu getJMenuAbout()

if(jMenuAbout == null)

jMenuAbout = new JMenu();

jMenuAbout.setText("?");

jMenuAbout.add(getJMenuAboutDialog());
}

return jMenuAbout;

protected JMenuItem getJMenuAboutDialog()

if(jMenuAboutDialog == null)

jMenuAboutDialog = new JMenuItem();

jMenuAboutDialog.setText("About me");

jMenuAboutDialog.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

new AboutMeDialog(ChatFrame.this, false,

true, "TCP Client/Server Chat", new


String[]{}).setVisible(true);

});

return jMenuAboutDialog;

protected abstract JMenu getJMenuActions();

protected abstract void attachEvents();

protected abstract void initializeEnd();

protected abstract void refreshInfo();

/**

* Print in the GUI a text formatted

*/
protected void print(String message)

HtmlString text = new HtmlString(getJTextReceive().getText());

//Insert the message and a horizontal barre in the HTML String

text.insert(message+"<HR>");

getJTextReceive().setText(text.getHtmlCode());

/**

* Prints text in the console

*/

protected void printDebug(String s)

if(DEBUG_MODE)

System.out.println("DEBUG : "+s);

Client.Java
package org.jouvieje.network.Chat;

import java.awt.event.*;

import java.io.IOException;

import java.io.InputStream;

import java.util.StringTokenizer;

import java.util.Vector;

import javax.swing.*;

import org.jouvieje.network.*;

import org.jouvieje.network.parser.html.HtmlString;
import static org.jouvieje.network.Chat.protocol.Decoder.*;

import static org.jouvieje.network.Chat.protocol.Encoder.*;

public class Client extends ChatFrame<ClientConnection>

private Thread listener = null;

private JMenu jMenuActions = null;

private JMenuItem jMenuDisconnect = null;

public Client(ClientConnection user, String pseudo)

super(user, pseudo);

user.setProtocol(getProtocol());

initialize();

private void initialize()

this.setJMenuBar(getJJMenuBar());

this.setTitle("TCP Client/Server Chat - Client - Made by Manish Mitra");

this.setSize(500, 350);

this.setContentPane(getJContentPane());

this.setLocationRelativeTo(null);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setResizable(true);

this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {

if(user.isConnected())

disconnectClient(false);

});

protected void initializeEnd()

getJInfoSend().setText("Message to send");

getJInfoReceive().setText("Message Received");

getJTextSend().setText("Write your message here.\nSelect the addressee and


send it !");

refreshInfo();

protected void attachEvents()

getJButtonSend().addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String to = (String)getJPseudos().getSelectedItem();

String message = getJTextSend().getText();

if(message != null)

message =
HtmlString.toHtmlString(message).getBody();

String messageFormatted = encodeMessage(pseudo, to,


message);
boolean sended = send(messageFormatted);

printOutput(to, message, sended);

});

getJButtonConnect().addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

getJButtonConnect().setEnabled(false);

if(user.connect())

//Start the thread that accepts clients

getListener().start();

//Refresh connection info

refreshInfo();

getJButtonConnect().setEnabled(false);

getJMenuDisconnect().setEnabled(true);

else

JOptionPane.showMessageDialog(Client.this,
"<HTML>Server may not be ready.<BR>Try to connect at another time.</HTML>");

getJButtonConnect().setEnabled(true);

getJMenuDisconnect().setEnabled(false);

});
}

/**

* @return connection information stored in a String formated in HTML to be drawn


in a swing graphical.

*/

protected void refreshInfo()

String info = "<B><U>Connection informations :</U></B> Your pseudo is


"+pseudo;

if(user.isConnected())

info += "<br>You are connected.";

if(getJPseudos().getItemCount() == 1)

info += " 1 user connected to the Chat server.";

else if(getJPseudos().getItemCount() > 1)

info += " "+getJPseudos().getItemCount()+" users connected to


the Chat server.";

else

info += " You are the only user connected on the Chat
server !";

else

info += "<br>You are not connected !";

info = "<HTML>"+info+"<BR>&nbsp;</HTML>";

getJInfoL().setText(info);

protected JMenu getJMenuActions()

if(jMenuActions == null)

{
jMenuActions = new JMenu();

jMenuActions.setText("Actions");

jMenuActions.add(getJMenuDisconnect());

return jMenuActions;

private JMenuItem getJMenuDisconnect()

if(jMenuDisconnect == null)

jMenuDisconnect = new JMenuItem();

jMenuDisconnect.setText("Disconnect");

jMenuDisconnect.setEnabled(false);

jMenuDisconnect.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

disconnectClient(false);

});

return jMenuDisconnect;

/*******************************************/

/**

* @return the thread used to read received datas

*/
protected Thread getListener()

if(listener == null)

//Creating the thread

listener = new Thread() {

public void run()

//Loop that receive datas

boolean end = false;

while(!end)

try

//Equivalent to : if(user.hasInput()
user.getProtocol.processInput(...);

user.checkInput();

catch(IOException e)

end = true;

try

Thread.sleep(20);

catch(InterruptedException e){}

}
user.disconnect();

};

return listener;

/**

* All data recevied are passed through this method.<BR>

* This method decodes input message and execute what things should be done.

*/

public Protocol getProtocol()

return new Protocol(){

public void processInput(InputStream in)

//Read inputs

String datas = "";

try

while(in.available() > 0)

datas += new String(user.readInput());

catch(IOException e)

return;

datas = datas.trim();

printDebug("DATA RECEIVED : "+datas);


//Decode datas

Vector<TagValue> queries = decodeTag(datas);

//Process inputs

for(TagValue tagValue : queries)

switch(tagValue.tag)

case REQUEST:

if(Request.valueOf(tagValue.value) ==
Request.PSEUDO)

printDebug("Your pseudo is
requested");

send(encodeTag(Tag.PSEUDO,
pseudo));

else if(Request.valueOf(tagValue.value)
== Request.DISCONNECTION)

disconnectClient(true);

JOptionPane.showMessageDialog(Client.this, "You are disconnected by the


server !");

break;

case MESSAGE:

String from = decodeField(Field.FROM,


tagValue.value);
String message =
decodeField(Field.BODY, tagValue.value);

printInput(from, message);

break;

case PSEUDO_LIST:

//Decoding pseudoList string and store it


in a vector

Vector<String> pseudos = new


Vector<String>();

StringTokenizer tokens = new


StringTokenizer(tagValue.value);

while(tokens.hasMoreTokens())

String newPseudo =
tokens.nextToken().replace(pseudoSeparatorCode, pseudoSeparator);

if(!newPseudo.equals(pseudo))

pseudos.add(newPseudo);

refreshPseudos(pseudos);

break;

case INFO:

JOptionPane.showMessageDialog(Client.this,
"<HTML>"+tagValue.value+"</HTML>");

break;

};

}
/**

* Send datas to the server

* @param datas datas to send

* @return true if datas was send

*/

protected boolean send(String datas)

try

return user.send(datas) > -1;

catch(IOException e)

printDebug("Send fails");

return false;

/*******************************************/

/**

* Print in the GUI a message received

*/

private void printInput(String from, String message)

//Format the message using HTML tags

print("<P><U><B>Message from "+from+" :


</B></U><BR>"+message+"</P>");
}

/**

* Print in the GUI a message received

*/

private void printOutput(String to, String message, boolean sended)

if(sended)

print("<P><I><U><B>Message sended to "+to+

" : </B></U><BR>"+message+"</I></P>");

else

print("<P><I><U><B><FONT COLOR=red>Fails to sended to "+to+

" : </FONT ></B></U><BR>"+message+"</I></P>");

/**

* Refresh pseudo list

* @param pseudos new list of pseudo

*/

private void refreshPseudos(Vector pseudos)

//Add new items

getJPseudos().setModel(new DefaultComboBoxModel(pseudos));

//Enable or disable send button

getJPseudos().setEnabled(pseudos.size() > 0);

getJButtonSend().setEnabled(pseudos.size() > 0);

//Refresh informations

refreshInfo();
}

/**

* Disconnect the client

* @param serverInformed true if the server is not informed of the client


disconnection

*/

protected void disconnectClient(boolean serverInformed)

printDebug("You will be disconnected !");

//Inform the server of the client disconnection

if(!serverInformed)

send(encodeRequest(Request.DISCONNECTION));

//Close connection

user.disconnect();

listener = null;

//Reset all components

refreshPseudos(new Vector());

getJButtonConnect().setEnabled(true);

getJMenuDisconnect().setEnabled(false);

IntroFrame.java
package org.jouvieje.network.Chat;

import javax.swing.JFrame;
/**

* Introduction frame that display information on the author (me)

* and ask the user if it is the server or a client.

*/

public class IntroFrame extends JFrame

private javax.swing.JPanel jContentPane = null;

private javax.swing.JLabel jLabelTitle = null;

private javax.swing.JLabel jLabelInfo = null;

private javax.swing.JLabel jLabelQuestion = null;

private javax.swing.JButton jButtonServer = null;

private javax.swing.JButton jButtonClient = null;

public IntroFrame()

super();

initialize();

private void initialize()

this.setSize(295, 200);

this.setContentPane(getJContentPane());

this.setTitle("TCP Client/Server Chat - Intro - Made by Manish Mitra");

this.setLocationRelativeTo(null);

this.setResizable(false);

this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

}
private javax.swing.JPanel getJContentPane()

if (jContentPane == null)

jContentPane = new javax.swing.JPanel();

jContentPane.setLayout(null);

jContentPane.add(getJLabelTitle());

jContentPane.add(getJLabelInfo());

jContentPane.add(getJLabelQuestion());

jContentPane.add(getJButtonServer());

jContentPane.add(getJButtonClient());

return jContentPane;

private javax.swing.JLabel getJLabelTitle()

if(jLabelTitle == null)

jLabelTitle = new javax.swing.JLabel();

jLabelTitle.setText("TCP Client/Server Chat");

jLabelTitle.setBounds(0, 0, 295, 20);

jLabelTitle.setVerticalAlignment(javax.swing.SwingConstants.TOP);

jLabelTitle.setHorizontalAlignment

(javax.swing.SwingConstants.CENTER);

jLabelTitle.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD,

14));
}

return jLabelTitle;

private javax.swing.JLabel getJLabelInfo()

if(jLabelInfo == null)

jLabelInfo = new javax.swing.JLabel();

jLabelInfo.setText("<HTML><BODY>Author : Manish
Mitra<BR><BR>E-Mail :

<A HREF=\"manish.bvc@gmail.com\">manish.bvc@gmail.com</A>");

jLabelInfo.setBounds(10, 20, 265, 85);

jLabelInfo.setVerticalAlignment(javax.swing.SwingConstants.TOP);

jLabelInfo.setVerticalTextPosition(javax.swing.SwingConstants.TOP);

return jLabelInfo;

private javax.swing.JLabel getJLabelQuestion()

if(jLabelQuestion == null)

jLabelQuestion = new javax.swing.JLabel();

jLabelQuestion.setText("Who are you ?");

jLabelQuestion.setBounds(15, 115, 88, 16);

return jLabelQuestion;

private javax.swing.JButton getJButtonServer()


{

if(jButtonServer == null)

jButtonServer = new javax.swing.JButton();

jButtonServer.setText("The Server");

jButtonServer.setBounds(30, 138, 96, 26);

jButtonServer.addActionListener(new java.awt.event.ActionListener()
{

public void actionPerformed(java.awt.event.ActionEvent e) {

new SettingsFrame(true).setVisible(true);

IntroFrame.this.dispose();

});

return jButtonServer;

private javax.swing.JButton getJButtonClient()

if(jButtonClient == null)

jButtonClient = new javax.swing.JButton();

jButtonClient.setText("The Client");

jButtonClient.setBounds(159, 138, 96, 26);

jButtonClient.addActionListener(new java.awt.event.ActionListener()
{

public void actionPerformed(java.awt.event.ActionEvent e) {

new SettingsFrame(false).setVisible(true);

IntroFrame.this.dispose();

}
});

return jButtonClient;

Ippanel.Java
package org.jouvieje.network.Chat;

import java.awt.Component;

import java.awt.Container;

import java.awt.FocusTraversalPolicy;

import java.awt.event.FocusEvent;

import javax.swing.JPanel;

import javax.swing.JTextField;

/**

* Componant that allow you to get an IP Address that contains 8 octets.

*/

class IpPanel extends JPanel

private javax.swing.JTextField jIp1 = null;

private javax.swing.JLabel jIpSeparator12 = null;

private javax.swing.JTextField jIp2 = null;

private javax.swing.JLabel jIpSeparator23 = null;

private javax.swing.JTextField jIp3 = null;

private javax.swing.JLabel jIpSeparator34 = null;

private javax.swing.JTextField jIp4 = null;


/**

* Used to know which component should be focus when tab key is pressed.

* (setNextFocusableComponent is deprecated)

*/

private FocusTraversalPolicy nextFocus = new FocusTraversalPolicy() {

public Component getComponentAfter(Container focusCycleRoot,


Component aComponent)

if(focusCycleRoot.equals(getJIp1()))

return getJIp2();

else if(focusCycleRoot.equals(getJIp2()))

return getJIp3();

else if(focusCycleRoot.equals(getJIp3()))

return getJIp4();

else if(focusCycleRoot.equals(getJIp4()))

return getJIp1();

return null;

public Component getComponentBefore(Container focusCycleRoot,


Component aComponent)

if(focusCycleRoot.equals(getJIp1()))

return getJIp4();

else if(focusCycleRoot.equals(getJIp2()))

return getJIp1();

else if(focusCycleRoot.equals(getJIp3()))

return getJIp2();

else if(focusCycleRoot.equals(getJIp4()))

return getJIp3();
return null;

public Component getDefaultComponent(Container focusCycleRoot)

return getFirstComponent(focusCycleRoot);

public Component getFirstComponent(Container focusCycleRoot)

return getJIp1();

public Component getLastComponent(Container focusCycleRoot)

return getJIp4();

};

/**

* Default constructor

*/

public IpPanel()

super();

initialize();

/**

* This method initializes this

* @return void

*/
private void initialize()

this.setSize(144, 22);

this.setPreferredSize(new java.awt.Dimension(144,22));

this.setLayout(null);

this.add(getJIp1(), null);

this.add(getJIpSeparator12(), null);

this.add(getJIp2(), null);

this.add(getJIpSeparator23(), null);

this.add(getJIp3(), null);

this.add(getJIpSeparator34(), null);

this.add(getJIp4(), null);

/**

* This method initializes jIp1

* @return javax.swing.JTextField

*/

private javax.swing.JTextField getJIp1()

if(jIp1 == null)

jIp1 = new javax.swing.JTextField();

jIp1.setFocusTraversalPolicy(nextFocus);

jIp1.setSize(30, 22);

jIp1.setLocation(0, 0);

jIp1.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent e) {

IpPanel.this.keyReleased(e);
}

});

jIp1.addFocusListener(new java.awt.event.FocusListener() {

public void focusLost(java.awt.event.FocusEvent e) {

IpPanel.this.focusLost(e);

public void focusGained(java.awt.event.FocusEvent e) {

IpPanel.this.focusGained(e);

});

return jIp1;

/**

* This method initializes jIpSeparator12

* @return javax.swing.JLabel

*/

private javax.swing.JLabel getJIpSeparator12()

if(jIpSeparator12 == null)

jIpSeparator12 = new javax.swing.JLabel();

jIpSeparator12.setSize(8, 22);

jIpSeparator12.setText(".");

jIpSeparator12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

jIpSeparator12.setLocation(30, 0);

return jIpSeparator12;
}

/**

* This method initializes jIp2

* @return javax.swing.JTextField

*/

private javax.swing.JTextField getJIp2()

if(jIp2 == null)

jIp2 = new javax.swing.JTextField();

jIp2.setFocusTraversalPolicy(nextFocus);;

jIp2.setSize(30, 22);

jIp2.setLocation(38, 0);

jIp2.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent e) {

IpPanel.this.keyReleased(e);

});

jIp2.addFocusListener(new java.awt.event.FocusListener() {

public void focusLost(java.awt.event.FocusEvent e) {

IpPanel.this.focusLost(e);

public void focusGained(java.awt.event.FocusEvent e) {

IpPanel.this.focusGained(e);

});

return jIp2;
}

/**

* This method initializes jIpSeparator23

* @return javax.swing.JLabel

*/

private javax.swing.JLabel getJIpSeparator23()

if(jIpSeparator23 == null)

jIpSeparator23 = new javax.swing.JLabel();

jIpSeparator23.setSize(8, 22);

jIpSeparator23.setText(".");

jIpSeparator23.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

jIpSeparator23.setLocation(68, 0);

return jIpSeparator23;

/**

* This method initializes jIp3

* @return javax.swing.JTextField

*/

private javax.swing.JTextField getJIp3()

if(jIp3 == null)

jIp3 = new javax.swing.JTextField();

jIp3.setFocusTraversalPolicy(nextFocus);;

jIp3.setSize(30, 22);
jIp3.setLocation(76, 0);

jIp3.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent e) {

IpPanel.this.keyReleased(e);

});

jIp3.addFocusListener(new java.awt.event.FocusListener() {

public void focusLost(java.awt.event.FocusEvent e) {

IpPanel.this.focusLost(e);

public void focusGained(java.awt.event.FocusEvent e) {

IpPanel.this.focusGained(e);

});

return jIp3;

/**

* This method initializes jIpSeparator34

* @return javax.swing.JLabel

*/

private javax.swing.JLabel getJIpSeparator34()

if(jIpSeparator34 == null)

jIpSeparator34 = new javax.swing.JLabel();

jIpSeparator34.setSize(8, 22);

jIpSeparator34.setText(".");
jIpSeparator34.setLocation(106, 0);

jIpSeparator34.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

return jIpSeparator34;

/**

* This method initializes jIp4

* @return javax.swing.JTextField

*/

private javax.swing.JTextField getJIp4()

if(jIp4 == null)

jIp4 = new javax.swing.JTextField();

jIp4.setSize(30, 22);

jIp4.setLocation(114, 0);

jIp4.setFocusTraversalPolicy(nextFocus);

jIp4.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent e) {

IpPanel.this.keyReleased(e);

});

jIp4.addFocusListener(new java.awt.event.FocusListener() {

public void focusLost(java.awt.event.FocusEvent e) {

IpPanel.this.focusLost(e);

public void focusGained(java.awt.event.FocusEvent e) {


IpPanel.this.focusGained(e);

});

return jIp4;

public void keyReleased(java.awt.event.KeyEvent e)

if(e.getComponent() instanceof JTextField)

if(((JTextField)e.getComponent()).getText().length() >= 3)

((JTextField)e.getComponent()).transferFocus();

verifyInput(((JTextField)e.getComponent()), true);

else

verifyInput(((JTextField)e.getComponent()), false);

public void focusLost(FocusEvent e)

if(e.getComponent() instanceof JTextField)

verifyInput((JTextField)e.getComponent(), true);

}
}

public void focusGained(FocusEvent e){}

/**

* @return the value of the IP address.<BR>

* null if the IP is incorrect

*/

public String getValue()

try

int dns1 = Integer.parseInt(getJIp1().getText());

int dns2 = Integer.parseInt(getJIp2().getText());

int dns3 = Integer.parseInt(getJIp3().getText());

int dns4 = Integer.parseInt(getJIp4().getText());

return dns1+"."+dns2+"."+dns3+"."+dns4;

catch(NumberFormatException e)

return null;

/**

* Redefine the setEnabled method of IpPanel

*/

public void setEnabled(boolean enabled)

{
super.setEnabled(enabled);

getJIp1().setEnabled(enabled);

getJIp2().setEnabled(enabled);

getJIp3().setEnabled(enabled);

getJIp4().setEnabled(enabled);

/**

* Verify the value of the JTextField component

* @return false if the value of the component is wrong

*/

private void verifyInput(JTextField jtf, boolean modify)

try

int value = Integer.parseInt(jtf.getText());

if(modify)

if(value >= 255)

jtf.setText("255");

else

jtf.setText(""+value);

catch(Exception e)

jtf.setText("");
}

Server.Java
package org.jouvieje.network.Chat;

import java.awt.*;

import java.awt.event.*;

import java.io.IOException;

import java.io.InputStream;

import java.net.Socket;

import java.util.Vector;

import javax.swing.*;

import org.jouvieje.network.*;

import org.jouvieje.network.Chat.protocol.ChatServerLink;

import org.jouvieje.network.parser.html.HtmlString;

import static org.jouvieje.network.Chat.protocol.Decoder.*;

import static org.jouvieje.network.Chat.protocol.Encoder.*;

public class Server extends ChatFrame<ServerConnection<ChatServerLink>>

public static final String SERVER_PSEUDO = "Chat administrator";

public static final String TEMP_PSEUDO = "Unidentified user ";

public static final String ALL_USERS = "All users identified";


private Thread acceptClientsThread = null;

private JButton jButtonSendAll = null;

private JMenu jMenuActions = null;

private JMenuItem jMenuDisconnectClient = null;

private JMenuItem jMenuDisconnectAllClients = null;

private JMenuItem jMenuCloseServer = null;

private JCheckBoxMenuItem jCheckAcceptAllClients = null;

public Server(ServerConnection<ChatServerLink> user)

super(user, SERVER_PSEUDO);

user.setServerLinkCreator(new ServerLinkCreator<ChatServerLink>() {

public ChatServerLink create(Socket socket) throws IOException

ChatServerLink clientLink = new ChatServerLink(socket);

attachListener(clientLink);

attachProtocol(clientLink);

return clientLink;

});

initialize();

protected void initialize()

this.setTitle("TCP Client/Server Chat - Server - Made by Manish Mitra");

this.setSize(500, 350);
this.setContentPane(getJContentPane());

this.setJMenuBar(getJJMenuBar());

this.setLocationRelativeTo(null);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setResizable(true);

this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

if(user.isConnected())

disconnect(false);

});

protected void initializeEnd()

getJPanelSendButtons().add(getJButtonSendAll(), BorderLayout.EAST);

getJInfoSend().setText("Info to send");

getJTextSend().setText("Write an info to a user here.\nClients will be inform


of this message in a dialog box.");

getJInfoReceive().setText("Message transmitted");

refreshInfo();

protected void attachEvents()

getJButtonSend().addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

ChatServerLink client =
getClientLink((String)getJPseudos().getSelectedItem());
String info = getJTextSend().getText();

if(info != null && client != null)

String infoFormatted =
HtmlString.toHtmlString(info).getBody();

infoFormatted = encodeTag(Tag.INFO, infoFormatted);

boolean sended = send(client, infoFormatted);

printInfo(client.getPseudo(), info, sended);

});

getJButtonConnect().addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

getJButtonConnect().setEnabled(false);

if(user.connect())

//Start the thread that accepts clients

getAcceptClientsThread().start();

//Refresh connection info

refreshInfo();

getJMenuCloseServer().setEnabled(true);

else

JOptionPane.showMessageDialog(Server.this,
"<HTML>Fails to open the server !<BR>Please restart the application.</HTML>");
getJButtonConnect().setEnabled(true);

});

protected void refreshInfo()

String info = "<B><U>Connection informations :</U></B>";

if(user.isConnected())

info += " You're listening on the port "+user.getLocalPort();

if(user.getLinkCount() >= 1)

info += "<br> "+user.getLinkCount()+" client(s) connected.";

else

info += "<br> No client connected !";

ChatServerLink client =
getClientLink((String)getJPseudos().getSelectedItem());

if(client != null && client.isConnected())

if(client.isAuthentified())

info += "<br>The user "+client.getPseudo()+" is


identified.";

else

info += "<br>The user "+client.getPseudo()+" is not


identified.";

info += " He's IP is : "+client.getRemoteIP()+" he's port is :


"+client.getRemotePort();

}
else

info += " You are not connected !";

info = "<HTML>"+info+"<BR>&nbsp;</HTML>";

getJInfoL().setText(info);

protected JButton getJButtonSendAll()

if(jButtonSendAll == null)

jButtonSendAll = new JButton();

jButtonSendAll.setText("Send All");

jButtonSendAll.setEnabled(false);

jButtonSendAll.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String info = getJTextSend().getText();

if(info != null)

String infoFormatted =
HtmlString.toHtmlString(info).getBody();

infoFormatted = encodeTag(Tag.INFO,
infoFormatted);

sendAll(infoFormatted);

printInfo("<B>"+ALL_USERS+"</B>", info,
true);

});

}
return jButtonSendAll;

protected JMenu getJMenuActions()

if(jMenuActions == null)

jMenuActions = new JMenu();

jMenuActions.setText("Actions");

jMenuActions.add(getJCheckAcceptAllClients());

jMenuActions.addSeparator();

jMenuActions.add(getJMenuDisconnectClient());

jMenuActions.add(getJMenuDisconnectAllClients());

jMenuActions.addSeparator();

jMenuActions.add(getJMenuCloseServer());

return jMenuActions;

private JCheckBoxMenuItem getJCheckAcceptAllClients()

if(jCheckAcceptAllClients == null)

jCheckAcceptAllClients = new JCheckBoxMenuItem();

jCheckAcceptAllClients.setText("Accept all clients");

jCheckAcceptAllClients.setSelected(false);

return jCheckAcceptAllClients;

private JMenuItem getJMenuDisconnectClient()


{

if(jMenuDisconnectClient == null)

jMenuDisconnectClient = new JMenuItem();

jMenuDisconnectClient.setText("Disconnect a client");

jMenuDisconnectClient.setEnabled(false);

jMenuDisconnectClient.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

if(getJPseudos().getSelectedIndex() >= 0)

ChatServerLink client =
getClientLink((String)getJPseudos().getSelectedItem());

disconnectClient(client, false);

printDisconnect(client.getPseudo());

});

return jMenuDisconnectClient;

private JMenuItem getJMenuDisconnectAllClients()

if(jMenuDisconnectAllClients == null)

jMenuDisconnectAllClients = new JMenuItem();

jMenuDisconnectAllClients.setText("Disconnect all clients");

jMenuDisconnectAllClients.setEnabled(false);

jMenuDisconnectAllClients.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

if(getJPseudos().getSelectedIndex() >= 0)

disconnectAllClient();

});

return jMenuDisconnectAllClients;

private JMenuItem getJMenuCloseServer()

if(jMenuCloseServer == null)

jMenuCloseServer = new JMenuItem();

jMenuCloseServer.setText("Close server");

jMenuCloseServer.setEnabled(false);

jMenuCloseServer.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)

disconnect(true);

});

return jMenuCloseServer;

/*******************************************/
/**

* This thread accept clients that tries to connect to the server.<BR>

* When a user is connected, the server can choose if the client is accepted.

*/

private Thread getAcceptClientsThread()

if(acceptClientsThread == null)

acceptClientsThread = new Thread()

public void run()

while(user.isConnected())

ChatServerLink client = null;

if((client = user.acceptConnection() ) != null)

/*

* Request client pseudo

*/

String pseudoRequest =
encodeRequest(Request.PSEUDO);

printDebug("Requesting pseudo");

send(client, pseudoRequest);

//Affect a temporary pseudo to the client

String tempPseudo =
TEMP_PSEUDO+user.getLinkCount();
client.setPseudo(tempPseudo);

getJPseudos().addItem(tempPseudo);

//Start the thread that receive message

client.getListener().start();

};

return acceptClientsThread;

/**

* Attach a thread that read received datas to a ClientLink

*/

protected void attachListener(final ChatServerLink client)

client.setListener(new Thread() {

public void run()

boolean end = false;

while(!end)

try

//Equivalent to : if(user.hasInput()
user.getProtocol.processInput(...);

client.checkInput();
}

catch(IOException e)

end = true;

try

Thread.sleep(20);

catch(InterruptedException e){}

user.disconnectLink(client);

});

/**

* Attach a communication protocol to a ClientLink

*/

protected void attachProtocol(final ChatServerLink clientLink)

clientLink.setProtocol(new Protocol() {

//Keeps in mind in which CLientLink this Protocol is attached

private ChatServerLink client = clientLink;

/**

* All data recevied are passed through this method.<BR>

* This method decodes input message and execute what things should
be done.

*/
public void processInput(InputStream in)

//Read inputs

String datas = null;

try

while(in.available() > 0)

datas += new String(client.readInput());

catch(IOException e)

return;

datas = datas.trim();

printDebug("DATA RECEIVED : "+datas);

Vector<TagValue> queries = decodeTag(datas);

for(TagValue tagValue : queries)

if(client.isAuthentified())

switch(tagValue.tag)

case REQUEST:

if(Request.valueOf(tagValue.value) == Request.DISCONNECTION)

disconnectClient(client,
true);
printDisconnect(client.getPseudo());

JOptionPane.showMessageDialog(Server.this, client.getPseudo()+" is
disconnected !");

break;

case MESSAGE:

String sender =
decodeField(Field.FROM, datas);

String to =
decodeField(Field.TO, datas);

String message =
decodeField(Field.BODY, datas);

//Redirection of the message to


its addressee

ChatServerLink receiver =
getClientLink(to);

boolean sended = false;

if(receiver != null)

sended = send(receiver,
encodeMessage(sender, to, message));

if(sended)

printMessage(sender, to,
message, sended);

else if(receiver == null)

{
//Inform that the receiver
is not found

String info =
encodeTag(Tag.INFO, "<HTML>Addressee ("+to+") of this message does not exists
:<BR>"+message+"</HTML>");

sended = send(client,
info);

printInfo(sender, info,
sended);

break;

else

if(tagValue.tag == Tag.PSEUDO)

String clientPseudo = tagValue.value;

printDebug("Receiving identification :
"+clientPseudo);

if(!isPseudoValide(clientPseudo))

boolean accepted = false;

if(getJCheckAcceptAllClients().isSelected())

accepted = true;

else
{

/*

* Ask to the server if he


wants to accept the new user authenticated.

* Normally, this is done


automaticly. For exampls, by searching in a data base

* if the used is
registered ... But, for this tutorial, I let the server doing this job.

*/

int choice =
JOptionPane.showConfirmDialog(Server.this, "<html>New user identified :
"+clientPseudo+"<br>Do you want to accept him ?</html>", "New user",
JOptionPane.YES_NO_OPTION);

accepted = (choice ==
JOptionPane.YES_OPTION);

if(accepted)

//Register the pseudo of


the client

client.setPseudo(clientPseudo);

client.setAuthentified(true);

//Change value of the


item

sendPseudoList();

else

disconnectClient(client,
false);

}
}

else

printDebug("A user tries to use


an existing or a wrong pseudo !");

//Tell that the client use an


existing pseudo

String info =
encodeTag(Tag.INFO, "<HTML>Your pseudo is invalide (already exists or contains the
sequence "+

pseudoSeparatorCode+").<BR>Please use a different pseudo.<BR><BR>You will be


disconnected !</HTML>");

boolean sended = send(client,


info);

printInfo(client.getPseudo(), info,
sended);

//Eject it !

disconnectClient(client, false);

else

//Inform that datas received are not takes


in account

String info = encodeTag(Tag.INFO,


"<HTML>Your message is not takes in account.<BR>You MUST identify
yourself.</HTML>");

boolean sended = send(client, info);

printInfo(client.getPseudo(), info,
sended);
//Send a request for the client pseudo

String pseudoRequest =
encodeRequest(Request.PSEUDO);

printDebug("Requesting pseudo");

send(client, pseudoRequest);

});

/**

* All sended datas pass through this method.

* @param index index of the client

* @param datas

*/

private boolean send(ChatServerLink client, String datas)

try

printDebug("DEBUG: Datas to send : "+datas);

return client.send(datas) > -1;

catch(IOException e)

return false;

}
}

/**

* Send datas to all users authentified

* @param datas datas to send

*/

private void sendAll(String datas)

for(ChatServerLink client : user.getLinks())

if(client.isAuthentified())

send(client, datas);

/*******************************************/

/**

* Print in the history panel the info sended

* @param to receiver

* @param info info

* @param sended is sended ?

*/

private void printInfo(String to, String info, boolean sended)

if(sended)

print("<P STYLE=\"background-color:#CCCCCC\"><I><U><B>Info
sended to "+to+" : </B></U><BR>"+info+"</I></P>");

else

print("<P STYLE=\"background-
color:#CCCCCC\"><I><U><B><FONT COLOR=red>Fail to send info to "+to+" :
</FONT></B></U><BR>"+info+"</I></P>");
}

/**

* Print in the history panel the message sended

* @param from sender

* @param to receiver

* @param message message

* @param sended is sended ?

*/

private void printMessage(String from, String to, String message, boolean sended)

if(sended)

print("<P><I><U><B>Message transmitted from "+from+" to "+to+

" : </B></U><BR>"+message+"</I></P>");

else

print("<P><I><U><B><FONT COLOR=red>Fails to transmitted


message from "+from+" to "+to+

" : </FONT></B></U><BR>"+message+"</I></P>");

/**

* Print a disconnection message

* @param to a client

* @param sended is sended ?

*/

private void printDisconnect(String to)

print("<P STYLE=\"background-color:#FF6666\"><I><U><B>"+to+" is
disconnected</B></U><BR></I></P>");

}
/**

* Update and send new pseudo list.

*/

private void sendPseudoList()

Vector<String> vector = new Vector<String>();

String pseudoList = "";

boolean first = true;

for(ChatServerLink client : user.getLinks())

vector.add(client.getPseudo());

if(client.isAuthentified())

if(!first)

pseudoList += pseudoSeparator;

pseudoList += client.getPseudo().replace(pseudoSeparator,
pseudoSeparatorCode);

first = false;

//Update gui

getJPseudos().setModel(new DefaultComboBoxModel(vector));

enableComponents(vector.size() > 0);

refreshInfo();

//Send new pseudo list to all clients

if(!first)

sendAll(encodeTag(Tag.PSEUDO_LIST, pseudoList));
}

private void enableComponents(boolean enable)

getJButtonSend().setEnabled(enable);

getJButtonSendAll().setEnabled(enable);

getJMenuDisconnectClient().setEnabled(enable);

getJMenuDisconnectAllClients().setEnabled(enable);

getJPseudos().setEnabled(enable);

/**

* @param pseudo pseudo to check

* @return true if the pseudo is valide

*/

private boolean isPseudoValide(String pseudo)

if(pseudo.indexOf(pseudoSeparatorCode) != -1)

return false;

return getClientLink(pseudo) != null;

/**

* @param pseudo pseudo of the client linked to the server

* @return the ChatClientLink by its client pseudo

*/

private ChatServerLink getClientLink(String pseudo)

for(ChatServerLink client : user.getLinks())


if(client.getPseudo().equals(pseudo))

return client;

return null;

/**

* Disconnect a client from the Chat server

* @param client client to be removed from the Chat server

* @param clientInformed know if the client is already informed of its disconnection.

*/

private void disconnectClient(ChatServerLink client, boolean clientInformed)

//Inform and disconnect the client

if(!clientInformed)

send(client, encodeRequest(Request.DISCONNECTION));

user.disconnectLink(client);

sendPseudoList();

/**

* Disconnect all clients from the Chat server

*/

private void disconnectAllClient()

//Inform and disconnect all clients

sendAll(encodeRequest(Request.DISCONNECTION));

user.disconnectAllLink();
//Reset gui

getJPseudos().setModel(new DefaultComboBoxModel());

printDisconnect(ALL_USERS);

/**

* Disconnect the server

* @param ask ask if the server should be closed

*/

private void disconnect(boolean ask)

if(ask)

int choice = JOptionPane.showConfirmDialog(this, "<HTML>If you


closing the server, you should restart the application before reconnection.<BR>" +

"Do you want to disconnect yourself ?</HTML>",


"Disconnection confirmation", JOptionPane.YES_NO_OPTION);

if(choice == JOptionPane.NO_OPTION)

return;

printDebug("You will be disconnected !");

//Inform that all clients will be ejected

sendAll(encodeRequest(Request.DISCONNECTION));
//Close connection

user.disconnect();

acceptClientsThread = null;

//Reset all components

getJPseudos().setModel(new DefaultComboBoxModel());

enableComponents(false);

getJButtonConnect().setEnabled(true);

getJMenuCloseServer().setEnabled(false);

refreshInfo();

ChatServerLink.java
package org.jouvieje.network.Chat.protocol;

import java.io.IOException;

import java.net.Socket;

import org.jouvieje.network.ServerLink;

public class ChatServerLink extends ServerLink

/** Pseudo of the client connected to the Link */

private String pseudo = null;

/** Client is authentified ? */

private boolean authentified = false;

/** Thread that listen for datas received */

protected Thread listener = null;

public ChatServerLink(Socket socket) throws IOException


{

super(socket);

/**

* @return the client pseudo connected to the server

*/

public String getPseudo()

return pseudo;

/**

* @param pseudo pseudo of the client connected to the server

*/

public void setPseudo(String pseudo)

this.pseudo = pseudo;

/**

* @return thread used to listen data received

*/

public Thread getListener()

return listener;

/**

* @param thread thread listening for data received


*/

public void setListener(Thread thread)

this.listener = thread;

/**

* @return true if the client is identified

*/

public boolean isAuthentified()

return authentified;

/**

* Defines if the client is idenfied or not

* @param identified new value of identified field

*/

public void setAuthentified(boolean identified)

this.authentified = identified;

Decoder.java
package org.jouvieje.network.Chat.protocol;

import java.util.Vector;

/**

* Decode datas received


*/

public class Decoder implements ProtocolEnums

public static Vector<TagValue> decodeTag(String datas)

Vector<TagValue> vector = new Vector<TagValue>();

int begin = 0;

int i, j, k;

while(begin < datas.length())

//Reading query opening

i = datas.indexOf("<", begin);

j = datas.indexOf(">", i+1);

if(i == -1 || j == -1)

throw new RuntimeException();

Tag query = Tag.valueOf(datas.substring(i+1, j));

//Reading query closing

k = datas.indexOf("</"+query+">", j);

if(k == -1)

throw new RuntimeException();

String value = datas.substring(j+1, k);

//Adding tag

vector.add(new TagValue(query, value));

begin = k+query.toString().length()+3;

}
return vector;

public static String decodeField(Field field, String datas)

int begin, end;

if(datas != null && (begin = datas.indexOf("<"+field+">")) != -1 &&

(end = datas.indexOf("</"+field+">")) != -1)

return datas.substring(begin+field.toString().length()+2, end);

return null;

Encoder.java
package org.jouvieje.network.Chat.protocol;

/**

* Encode datas to send

*/

public class Encoder implements ProtocolEnums

public static String encodeTag(Tag tag, String value)

if(tag == null || value== null)

return null;

return "<"+tag+">"+value+"</"+tag+">";

public static String encodeRequest(Request request)

{
if(request == null)

return null;

return "<"+Tag.REQUEST+">"+request+"</"+Tag.REQUEST+">";

public static String encodeMessage(String from, String to, String message)

String fromField = Encoder.encodeField(Field.FROM, from);

String toField = Encoder.encodeField(Field.TO, to);

String messageField = Encoder.encodeField(Field.BODY, message);

return Encoder.encodeTag(Tag.MESSAGE,
fromField+toField+messageField);

private static String encodeField(Field field, String value)

if(field == null || value== null)

return null;

return "<"+field+">"+value+"</"+field+">";

ProtocolEnums.java
package org.jouvieje.network.Chat.protocol;

public interface ProtocolEnums

public final static String pseudoSeparatorCode = "1_";

public final static String pseudoSeparator = " ";

public enum Tag


{

REQUEST,

MESSAGE,

PSEUDO,

PSEUDO_LIST,

INFO;

public enum Request

PSEUDO,

DISCONNECTION;

public enum Field

//Message fields

FROM,

TO,

BODY;

public class TagValue

public final Tag tag;

public final String value;

public TagValue(Tag query, String value)

this.tag = query;
this.value = value;

HtmlViewerDialog.java
package org.jouvieje.network.HtmlViewer;

import java.awt.Dialog;

import java.awt.Frame;

import java.net.URL;

import javax.swing.JDialog;

import javax.swing.JEditorPane;

import javax.swing.text.html.HTMLDocument;

import javax.swing.text.html.HTMLEditorKit;

public class HtmlViewerDialog extends JDialog

private final URL page;

private javax.swing.JPanel jContentPane = null;

private JEditorPane jEditorPane = null;

public HtmlViewerDialog(URL url)

this((Frame)null, false, url);

public HtmlViewerDialog(Frame frame, URL url)

this(frame, false, url);

}
public HtmlViewerDialog(Frame frame, boolean modal, URL url)

super(frame, modal);

page = url;

initialize();

public HtmlViewerDialog(Dialog dialog, URL url)

this(dialog, false, url);

public HtmlViewerDialog(Dialog dialog, boolean modal, URL url)

super(dialog, modal);

page = url;

initialize();

private void initialize()

this.setTitle("Light Html Viewer");

this.setSize(500, 400);

this.setResizable(true);

this.setLocationRelativeTo(null);

this.setContentPane(getJContentPane());

private javax.swing.JPanel getJContentPane()

{
if(jContentPane == null) {

jContentPane = new javax.swing.JPanel();

jContentPane.setLayout(new java.awt.BorderLayout());

jContentPane.add(getJEditorPane(),
java.awt.BorderLayout.CENTER);

return jContentPane;

private JEditorPane getJEditorPane()

if(jEditorPane == null)

jEditorPane = new JEditorPane();

jEditorPane.setDocument(new HTMLDocument());

jEditorPane.setEditorKit(new HTMLEditorKit());

try

jEditorPane.setPage(page);

catch(Exception e)

jEditorPane.setText("<HTML><BODY>Can't open the URL

:<BR>"+page.toString()+"</BODY></HTML>");

return jEditorPane;

}
}

HtmlString.java
package org.jouvieje.network.parser.html;

/**

* Light class to manipulates HTML code

*/

public class HtmlString

private String htmlCode = null;

private final String BLANK_PAGE = "<HTML><BODY></BODY></HTML>";

/**

* String that holds a blank page

*/

public HtmlString()

htmlCode = BLANK_PAGE;

/**

* Creates a new HTMLString with some HTML code.

* @param htmlCode String that contains html code

*/

public HtmlString(String htmlCode)

htmlCode = htmlCode.replaceAll("<Body>", "<BODY>");

htmlCode = htmlCode.replaceAll("<body>", "<BODY>");

htmlCode = htmlCode.replaceAll("</Body>", "</BODY>");


htmlCode = htmlCode.replaceAll("</body>", "</BODY>");

this.htmlCode = htmlCode;

public String toString()

return getHtmlCode();

/**

* @return the HTML code of the page

*/

public String getHtmlCode()

if(htmlCode == null)

htmlCode = BLANK_PAGE;

return htmlCode;

/**

* @return the body part of the page

*/

public String getBody()

return getHtmlCode().substring(getBodyStart(), getBodyEnd());

private int getBodyStart()

{
int index = getHtmlCode().indexOf("<BODY>");

return index+6;

private int getBodyEnd()

int index = getHtmlCode().lastIndexOf("</BODY>");

return index;

/**

* Insert HTML code at the end of the HTML page.

* @param code HTML code

*/

public void insert(String code)

htmlCode = getHtmlCode().replaceFirst("</BODY>", code+"</BODY>");

/*

* Replace line separator by <BR> tags

*/

private static String replaceLineSeparator(String text)

if(text == null)

return null;

return text.replaceAll(""+(char)10, "<BR>");

/**

* Add some text in a blank HTML page.


* @param text text to add in the page

* @return HTML page as an HtmlString object

*/

public static HtmlString toHtmlString(String text)

HtmlString htmlString = new HtmlString();

String newText = replaceLineSeparator(text);

htmlString.insert(newText);

return htmlString;

5.3 Testing Approach

Errors are relevant only after the system is in use. A system that has been put to use with out testing
can be disastrous in terns of the application. The importance of software testing and its implications
cannot be overemphasized. Software testing is a critical element of Software Quality Assurance and
represents the ultimate review of the specifications, design and coding.

Testing Objectives

The main objective of testing is to uncover a host of errors, systematically and with minimum effort
and time. Stating formally, we can say,

1. Testing is a process of executing a program with the intent of finding an error.


2. A successful test is one that uncovers an as yet undiscovered error.
3. A good test case is one that has a high probability of finding error, if it exists.

But there is one thing that testing cannot do (just to quote a very famous sentence) “Testing cannot
show the absence of defects, it can only show that software defects are presents.”

As the test results are gathered and evaluated they begin to give a qualitative indication of the
reliability of the software. If severe errors are detected, the overall quality of the software is a natural
suspect. If, on the other hand, all the errors, which are encountered, are easily modifiable, then one of
the two conclusions can be made:
• The tests are inadequate to detect possibly present errors.
• The software more or less confirms to the quality and reliable standards.

Levels of Testing

In order to uncover the errors present in different phases we have the concept of levels of
testing. The basic levels of testing are

Client Needs Acceptance Testing

Requirements System Testing

Design Integration Testing

Code Unit Testing

5.3.1 Unit testing

Unit testing focuses verification effort on the smallest unit of software i.e. the module. Using
the detailed design and the process specifications testing is done to uncover errors within the
boundary of the module. All modules must be successful in the unit test before the start of the
integration testing begins.
Each module has been tested by giving different sets of inputs (giving wrong ID and
password etc) when developing the module as well as finishing the development so That each
module works without any error. The inputs are validated when accepting from the user.

5.3.2 Integration Testing


After the unit testing we have to perform integration testing. The goal here is to see if modules can be
integrated properly, the emphasis being on testing interfaces between Modules. This testing activity
can be considered as testing the design and hence the emphasis on testing module interactions.
Integrating all the modules forms the main system. When integrating all the modules I have checked
whether the integration effects working of any of the services by giving different combinations of
inputs with which the two services run perfectly before Integration.

5.3.3 System Testing


Here the entire software system is tested. The reference document for this process is the requirements
document, and the goal is to see if software meets its requirements.
It has been tested against requirements of project and it is checked whether all requirements of project
have been satisfied or not.

5.3.4 Acceptance Testing


Acceptance Test is performed with realistic data of the client to demonstrate that the software is
working satisfactorily. Testing here is focused on external behavior of the system; the internal logic of
program is not emphasized.
Test cases should be selected so that the largest number of attributes of an equivalence class is
exercised at once. The testing phase is an important part of software development. It is the process of
finding errors and missing operations and also a complete verification to determine whether the
objectives are met and the user requirements are satisfied.

5.3.5 Test Plan


This document describes the plan for testing the course scheduling software. All major testing
activities are specified here. The test-plan is basically a list of test cases that need to be run on the
system. Some of the test cases can be run independently for some components (report generation from
the database, for example, can be tested independently) and some of the test cases require the whole
system to be ready for their execution. It is better to test each component as and when it is ready
before integrating the components. It is important to note that the test cases cover all the aspects of the
system (i.e., all the requirements stated in the RS document).
RESULTS AND DISCUSSIONS
6.1 Test Reports
Test Case ID Test Case description Expected Result Actual Result Pass/Fail

Test_001 Test Case to validate Connection to Server Same as Pass


that connection to should be established expected
Server is established successfully
successfully.

Test_002 Test Case to validate Clients should be Same as Pass


that, Clients are able to able to communicate expected
communicate with each with each other
other successfully successfully

Test_003 Test Case to validate Server should be able Same as Pass


that Server is able to to broad cast the expected
broad cast the message message to all the
to all the Clients Clients

Test_004 Test Case to validate Server should be able Same as Pass


that Server is able to to see all the expected
see all the connected connected Clients
Clients through LOV through LOV

Test_005 Test Case to validate Server should be able Same as Pass


that the server is able to to detect the client in expected
detect the client in case case the Client is
the Client is disconnected from
disconnected from the the session (Through
session (Through message)
message)

Test_006 Test Case to validate Clients should Same as Pass


that the Clients receives receive message expected
message whenever whenever Server is
Server is disconnected disconnected from
from the session the session

Test_007 Test Case to validate Client should be able Same as Pass


that Client is able to to save the chat log. expected
save the chat log.
6.2 User Documentation
Login Window

When we connect to the server after choosing “The Server” from the Login
Window
Once the server is established .Here the port is chosen to be as 1024
Here the client gives the login details of the server and gets connected to it.
The server gets a notification about the client and the server authenticates the
client.

This output shows the client status window after the client is connected to the
server.
Here the window shows Chat Communication between the Clients. The message
log in server is also displayed.
The Server sends the data to the clients and the same is shown as pooped up
window in the clients interface.

We could also save the chat log for the future reference,
This window is displayed when the client is disconnected from the server.
This window is displayed when the server is disconnected or killed
abruptly.

The Saved chat log in document. the saved document is in the HTML format.

CONCLUSIONS
7.1 Conclusion:
We have thus successfully implemented a Chat application as part of a Group Communications
application design under Networking. The application will enable easy communication between users
in an enterprise and at the same time, enable quick and fast access and cheaper communication media.
With more enhancements beyond the scope of this project, we can scale up the application to suit the
communication needs of a modern organization in a better way.

7.2 And 7.3 Limitations & Future Scope


The system designed by us cannot provide functionalities like file transfers, password settings, modes
of login like invisible, busy etc. that we see in commercial IM applications. We feel these are the
limitations of our project but the application can be scaled up to include these features as part of a
future study.
REFERENCES:
1. IGNOU Study Material (MCS-044)

2. WikiPedia

3. Java- A Complete Reference.

4. TCP/IP Architecture. (http://www.trainsignaltraining.com/networking-basics-tcp-


udp-tcpip-osi-models/2007-10-29/)

Das könnte Ihnen auch gefallen