project chat

Document Sample
project chat Powered By Docstoc
					                        Chat Room Project
                                          (E 2 0 0 4)




                                    Project Period

                  19th November to 17th December 2004


                  Supervised by Dan Witzner Hansen




                                             Group

                  Eswar Emmadi                                 120879-3345
                  Suresh kumar Dontha                          050381-3629


-------------------------------------------------------------------------------------------------------   1
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                            Contents

1. Introduction

2. Network Requirements & Java Platform

        TCP/ IP(Transmission Control Protocol/Internet Protocol)
        Java Sockets
        Thread & Synchronization
        Introduction to Client/Server model

3. User Interface

4. Design

5. Testing & Limitations

6. UML Diagrams & Source Code

7. Conclusion & Further Development

8. Reference Material




-------------------------------------------------------------------------------------------------------   2
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
 Introduction

        This chat room project is based on Client-server model, where client request the
server and server give response.

Server mainly deals with clients connection request, when user enters in chat room it will
check the username, whether this username exist in user list or not and it will informs all
the other users that a new user has entered in chat room similarly whenever user logoff it
will upgrade all online users user list.

The server broadcasts messages publicly to all online users or privately to a particular
user according to the attributes of the message send by clients

Client mainly requests connection to the known server(server ID and port is known)
It will sends the message to server stating that the message should be private or public
When it receives the message from server it will put into public or private text area
accordingly

When user logout it will send notice server that this user left the chat room

Clients uses Graphical User Interface to communicate with server. Client should know
the server ID when it requesting the server to communicate, after connecting to server
client can choose to chat privately or publicly by giving keyword to server.

Assumptions

        The application does not support peer-to-peer communication but only client-server
         communication i.e. two clients (or two users who have joined the chat) cannot
         communicate directly. All messages from the clients are sent to the server which then
         broadcasts it to all the clients currently connected to it.

        The server is started before the client can initiate a conversation with it.

        There is only one master, i.e. one server who controls the chat session.




-------------------------------------------------------------------------------------------------------   3
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
         Network Requirements & Java Platform

1. Introduction to TCP/IP
         TCP and IP were developed by a Department of Defense (DOD) research project
to connect a number different networks designed by different vendors into a network of
networks (the "Internet"). It was initially successful because it delivered a few basic
services that everyone needs (file transfer, electronic mail, remote logon) across a very
large number of client and server systems. Several computers in a small department can
use TCP/IP (along with other protocols) on a single LAN. The IP component provides
routing from the department to the enterprise network, then to regional networks, and
finally to the global Internet. On the battlefield a communications network will sustain
damage, so the DOD designed TCP/IP to be robust and automatically recover from any
node or phone line failure. This design allows the construction of very large networks
with less central management. However, because of the automatic recovery, network
problems can go undiagnosed and uncorrected for long periods of time.

As with all other communications protocol, TCP/IP is composed of layers:

        IP - is responsible for moving packet of data from node to node. IP forwards each
         packet based on a four byte destination address (the IP number). The Internet
         authorities assign ranges of numbers to different organizations. The organizations
         assign groups of their numbers to departments. IP operates on gateway machines
         that move data from department to organization to region and then around the
         world.
        TCP - is responsible for verifying the correct delivery of data from client to
         server. Data can be lost in the intermediate network. TCP adds support to detect
         errors or lost data and to trigger retransmission until the data is correctly and
         completely received.
        Sockets - is a name given to the package of subroutines that provide access to
         TCP/IP on most systems.

Network of Lowest Bidders
The Army puts out a bid on a computer and DEC wins the bid. T



.


-------------------------------------------------------------------------------------------------------   4
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
.

he Air Force puts out a bid and IBM wins. The Navy bid is won by Unisys. Then the
President decides to invade Grenada and the armed forces discover that their computers
cannot talk to each other. The DOD must build a "network" out of systems each of which,
by law, was delivered by the lowest bidder on a single contract.




The Internet Protocol was developed to create a Network of Networks (the "Internet").
Individual machines are first connected to a LAN (Ethernet or Token Ring). TCP/IP
shares the LAN with other uses (a Novell file server, Windows for Workgroups peer
systems). One device provides the TCP/IP connection between the LAN and the rest of
the world.

To insure that all types of systems from all vendors can communicate, TCP/IP is
absolutely standardized on the LAN. However, larger networks based on long distances
and phone lines are more volatile. In the US, many large corporations would wish to
reuse large internal networks based on IBM's SNA. In Europe, the national phone
companies traditionally standardize on X.25. However, the sudden explosion of high
speed microprocessors, fiber optics, and digital phone systems has created a burst of new

-------------------------------------------------------------------------------------------------------   5
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
options: ISDN, frame relay, FDDI, Asynchronous Transfer Mode (ATM). New
technologies arise and become obsolete within a few years. With cable TV and phone



companies competing to build the National Information Superhighway, no single
standard can govern citywide, nationwide, or worldwide communications.

The original design of TCP/IP as a Network of Networks fits nicely within the current
technological uncertainty. TCP/IP data can be sent across a LAN, or it can be carried
within an internal corporate SNA network, or it can piggyback on the cable TV service.
Furthermore, machines connected to any of these networks can communicate to any other
network through gateways supplied by the network vendor.

Addresses
       Each technology has its own convention for transmitting messages between two
machines within the same network. On a LAN, messages are sent between machines by
supplying the six byte unique identifier (the "MAC" address). In an SNA network, every
machine has Logical Units with their own network address. DECNET, Appletalk, and
Novell IPX

all have a scheme for assigning numbers to each local network and to each workstation
attached to the network.

On top of these local or vendor specific network addresses, TCP/IP assigns a unique
number to every workstation in the world. This "IP number" is a four byte value that, by
convention, is expressed by converting each byte into a decimal number (0 to 255) and
separating the bytes with a period. For example, the PC Lube and Tune server is
130.132.59.234.

An organization begins by sending electronic mail to Hostmaster@INTERNIC.NET
requesting assignment of a network number. It is still possible for almost anyone to get
assignment of a number for a small "Class C" network in which the first three bytes
identify the network and the last byte identifies the individual computer. The author
followed this procedure and was assigned the numbers 192.35.91.* for a network of
computers at his house. Larger organizations can get a "Class B" network where the first
two bytes identify the network and the last two bytes identify each of up to 64 thousand
individual workstations. Yale's Class B network is 130.132, so all computers with IP
address 130.132.*.* are connected through Yale.

The organization then connects to the Internet through one of a dozen regional or
specialized network suppliers. The network vendor is given the subscriber network
number and adds it to the routing configuration in its own machines and those of the
other major network suppliers.

-------------------------------------------------------------------------------------------------------   6
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
There is no mathematical formula that translates the numbers 192.35.91 or 130.132 into
"Yale University" or "New Haven, CT." The machines that manage large regional
networks or the central Internet routers managed by the National Science Foundation can



only locate these networks by looking each network number up in a table. There are
potentially thousands of Class B networks, and millions of Class C networks, but
computer memory costs are low, so the tables are reasonable. Customers that connect to
the Internet, even customers as large as IBM, do not need to maintain any information on
other networks. They send all external data to the regional carrier to which they
subscribe, and the regional carrier maintains the tables and does the appropriate routing.

New Haven is in a border state, split 50-50 between the Yankees and the Red Sox. In this
spirit, Yale recently switched its connection from the Middle Atlantic regional network to
the New England carrier. When the switch occurred, tables in the other regional areas and
in the national spine had to be updated, so that traffic for 130.132 was routed through
Boston instead of New Jersey. The large network carriers handle the paperwork and can

perform such a switch given sufficient notice. During a conversion period, the university
was connected to both networks so that messages could arrive through either path.

Need to Know
        There are three levels of TCP/IP knowledge. Those who administer a regional or
national network must design a system of long distance phone lines, dedicated routing
devices, and very large configuration files. They must know the IP numbers and physical
locations of thousands of subscriber networks. They must also have a formal network
monitor strategy to detect problems and respond quickly.

Each large company or university that subscribes to the Internet must have an
intermediate level of network organization and expertise. A half dozen routers might be
configured to connect several dozen departmental LANs in several buildings. All traffic
outside the organization would typically be routed to a single connection to a regional
network provider.

However, the end user can install TCP/IP on a personal computer without any knowledge
of either the corporate or regional network. Three pieces of information are required:

    1. The IP address assigned to this personal computer
    2. The part of the IP address (the subnet mask) that distinguishes other machines on
       the same LAN (messages can be sent to them directly) from machines in other
       departments or elsewhere in the world (which are sent to a router machine)
    3. The IP address of the router machine that connects this LAN to the rest of the
       world.

-------------------------------------------------------------------------------------------------------   7
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
In the case of the PCLT server, the IP address is 130.132.59.234. Since the first three
bytes designate this department, a "subnet mask" is defined as 255.255.255.0 (255 is the
largest byte value and represents the number with all bits turned on). It is a Yale
convention (which we recommend to everyone) that the router for each department have



station number 1 within the department network. Thus the PCLT router is 130.132.59.1.
Thus the PCLT server is configured with the values:

        My IP address: 130.132.59.234
        Subnet mask: 255.255.255.0
        Default router: 130.132.59.1



The subnet mask tells the server that any other machine with an IP address beginning
130.132.59.* is on the same department LAN, so messages are sent to it directly. Any IP
address beginning with a different value is accessed indirectly by sending the message
through the router at 130.132.59.1 (which is on the departmental LAN).

2.Java Sockets

         URLsand URLConnections provide a relatively high-level mechanism for
accessing resources on the Internet. Sometimes your programs require lower-level
network communication, for example, when you want to write a client-server
application.

In client-server applications, the server provides some service, such as processing
database queries or sending out current stock prices. The client uses the service
provided by the server, either displaying database query results to the user or
making stock purchase recommendations to an investor. The communication that
occurs between the client and the server must be reliable. That is, no data can be
dropped and it must arrive on the client side in the same order in which the server
sent it.

TCP provides a reliable, point-to-point communication channel that client-server
applications on the Internet use to communicate with each other. To communicate
over TCP, a client program and a server program establish a connection to one
another. Each program binds a socket to its end of the connection. To
communicate, the client and the server each reads from and writes to the socket
bound to the connection.

What is a Socket ?


-------------------------------------------------------------------------------------------------------   8
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
Normally, a server runs on a specific computer and has a socket that is bound to a
specific port number. The server just waits, listening to the socket for a client to
make a connection request.

On the client-side: The client knows the hostname of the machine on which the
server is running and the port number to which the server is connected. To make a



connection request, the client tries to rendezvous with the server on the server's
machine and port.




If everything goes well, the server accepts the connection. Upon acceptance, the
server gets a new socket bound to a different port. It needs a new socket (and
consequently a different port number) so that it can continue to listen to the
original socket for connection requests while tending to the needs of the
connected client.




On the client side, if the connection is accepted, a socket is successfully created
and the client can use the socket to communicate with the server. Note that the
socket on the client side is not bound to the port number used to rendezvous with
the server. Rather, the client is assigned a port number local to the machine on
which the client is running.


-------------------------------------------------------------------------------------------------------   9
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
The client and server can now communicate by writing to or reading from their
sockets.

Definition: A socket is one endpoint of a two-way communication link
between two programs running on the network. A socket is bound to a port
number so that the TCP layer can identify the application that data is
destined to be sent.



The java.net package in the Java platform provides a class, Socket, that implements
one side of a two-way connection between your Java program and another
program on the network. The Socket class sits on top of a platform-dependent
implementation, hiding the details of any particular system from your Java
program. By using the java.net.Socket class instead of relying on native code, your
Java programs can communicate over the network in a platform-independent
fashion.

Additionally, java.net includes the ServerSocket class, which implements a socket
that servers can use to listen for and accept connections to clients..




                                                             Client Program


            Server         Port
            Program        9999                              Client Program


                                                             Client Program




A server program typically provides resources to a network of client programs. Client
programs send requests to the server program, and the server program responds to the
request.

One way to handle requests from more than one client is to make the server program
multi-threaded. A multi-threaded server creates a thread for each communication it

------------------------------------------------------------------------------------------------------- 10
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
accepts from a client. A thread is a sequence of instructions that run independently of the
program and of any other threads.




3. Thread & Synchronization
What Is a Thread?
       All programmers are familiar with writing sequential programs. You've
probably written a program that displays "Hello World!" or sorts a list of names
or computes a list of prime numbers. These are sequential programs. That is, each
has a beginning, an execution sequence, and an end. At any given time during the
runtime of the program, there is a single point of execution.

A thread is similar to the sequential programs. A single thread also has a
beginning, a sequence, and an end and at any given time during the runtime of the
thread, there is a single point of execution. However, a thread itself is not a
program; it cannot run on its own. Rather, it runs within a program. The following
figure shows this relationship.




               Definition: A thread is a single sequential flow of control
        within a program.

There is nothing new in the concept of a single thread. The real hoopla
surrounding threads is not about a single sequential thread. Rather, it's about the
use of multiple threads in a single program, running at the same time and
performing different tasks. This is illustrated by the following figure:




------------------------------------------------------------------------------------------------------- 11
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
The HotJava Web browser is an example of a multithreaded application. Within
the HotJava browser you can scroll a page while it's downloading an applet or
image, play animation and sound concurrently, print a page in the background
while you download a new page, or watch three sorting algorithms race to the
finish. You are used to life operating in a concurrent fashion...so why not your
browser?

Some texts use the name lightweight process instead of thread. A thread is similar
to a real process in that a thread and a running program are both a single
sequential flow of control. However, a thread is considered lightweight because it
runs within the context of a full-blown program and takes advantage of the
resources allocated for that program and the program's environment.



As a sequential flow of control, a thread must carve out some of its own resources
within a running program. (It must have its own execution stack and program
counter for example.) The code running within the thread works only within that
context. Thus, some other texts use execution context as a synonym for thread.

The Life Cycle of a Thread
      Lets look at the Life cycle of a thread: how to create and start a thread,
some of the special things it can do while it's running, and how to stop it.

The following diagram shows the states that a Java thread can be in during its life.
It also illustrates which method calls cause a transition to another state. This
figure is not a complete finite state diagram, but rather an overview of the more
interesting and common facets of a thread's life. The remainder of this section
uses the Clock applet previously introduced to discuss a thread's life cycle in terms
of its state.




------------------------------------------------------------------------------------------------------- 12
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
Synchronizing Threads

        Each thread contained all of the data and methods required for its
execution and didn't require any outside resources or methods. In addition, the
threads ran at their own pace without concern over the state or activities of any
other concurrently running threads.

However, there are many interesting situations where separate, concurrently
running threads do share data and must consider the state and activities of other
threads. One such set of programming situations are known as producer/consumer
scenarios where the producer generates a stream of data which then is consumed
by a consumer.

For example, imagine a Java application where one thread (the producer) writes
data to a file while a second thread (the consumer) reads data from the same file.
Or, as you type characters on the keyboard, the producer thread places key events

in an event queue and the consumer thread reads the events from the same queue.
Both of these examples use concurrent threads that share a common resource: the
first shares a file, the second shares an event queue. Because the threads share a
common resource, they must be synchronized in some way.

Grouping Threads

        Every Java thread is a member of a thread group. Thread groups provide a
mechanism for collecting multiple threads into a single object and manipulating
those threads all at once, rather than individually. For example, you can start or
suspend all the threads within a group with a single method call. Java thread
groups are implemented by the Thread Group class in the java.lang package.

The runtime system puts a thread into a thread group during thread construction.
When you create a thread, you can either allow the runtime system to put the new
thread in some reasonable default group or you can


------------------------------------------------------------------------------------------------------- 13
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
explicitly set the new thread's group. The thread is a permanent member of
whatever thread group it joins upon its creation--you cannot move a thread to a
new group after the thread has been created.

The Default Thread Group

        If you create a new Thread without specifying its group in the constructor,
the runtime system automatically places the new thread in the same group as the
thread that created it (known as the current thread group and the current thread,
respectively). So, if you leave the thread group unspecified when you create your
thread, what group contains your thread?

When a Java application first starts up, the Java runtime system creates a
ThreadGroup named main. Unless specified otherwise, all new threads that you
create become members of the main thread group.



4. Client/Server Fundamentals

Definitions

       Client/server model is a concept for describing communications between
computing processes that are classified as service consumers (clients) and service
providers (servers). The below Figure presents a simple C/S model. The basic features of
a C/S model are:

             a. Clients and servers are functional modules with well defined interfaces
                (i.e., they hide internal information). The functions performed by a client
                and a server can be implemented by a set of software modules, hardware
                components, or a combination thereof. Clients and/or servers may run on
                dedicated machines, if needed. It is unfortunate that some machines are
                called "servers." This causes confusion (try explaining to an already
                bewildered user that a client’s software is running on a machine called
                "the server").
             b. Each client/server relationship is established between two functional
                modules when one module (client) initiates a service request and the other
                (server) chooses to respond to the service request. Examples of service
                requests (SRs) are "retrieve customer name", "produce net income in last
                year," etc. For a given service request, clients and servers do not reverse
                roles (i.e., a client stays a client and a server stays a server). However, a
                server for SR R1 may become a client for SR R2 when it issues requests to
             c. another server (see below Figure). For example, a client may issue an SR
                that may generate other SRs.


------------------------------------------------------------------------------------------------------- 14
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                 3. Information exchange between clients and servers is strictly through
                 messages (i.e., no information is exchanged through global variables). The
                 service request and additional information is placed into a message that is
                 sent to the server. The server's response is similarly another message that
                 is sent back to the client. This is an extremely crucial feature of C/S
                 model.

The following additional features, although not required, are typical of a client/server
model:

                 4. Messages exchanged are typically interactive. In other words, C/S
                 model does not support an off-line process. There are a few exceptions.
                 For example, message queuing systems allow clients to store messages on
                 a queue to be picked up asynchronously by the servers at a later stage.



                 5. Clients and servers typically reside on separate machines connected
                 through a network. Conceptually, clients and servers may run on the same
                 machine or on separate machines. However, our primary interest is in
                 distributed client/server systems where clients and servers reside on
                 separate machines.

The implication of the last two features is that C/S service requests are real-time
messages that are exchanged through network services. This feature increases the appeal
of the C/S model (i.e., flexibility, scalability) but introduces several technical issues such
as portability, interoperability, security, and performance.




------------------------------------------------------------------------------------------------------- 15
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
Conceptual Client/Server Model

Client/server applications, an area of vital importance to us, employ the C/S model to
deliver business aware functionalities. C/S applications provide a powerful and flexible
mechanism for organizations to design applications to fit the business needs. For
example, an order processing application can be implemented using the C/S model by
keeping the order processing databases (customers, products) at the corporate office and
developing/customizing the order processing logic and user interfaces for different stores
that initiate orders. In this case, order processing clients may reside on store computers to
perform initial checking and preprocessing, and the order processing servers may exist at
the corporate mainframe to perform final approval and shipping. Due to the critical

importance of C/S applications to business enterprises of the 1990s and beyond, we will
focus on C/S applications in this book.

Client/Server–A Special Case of Distributed Computing

Below Figure shows the interrelationships between distributed computing and
client/server models. Conceptually, client/server model is a special case of distributed-
computing model.




Interrelationships between Computing Models

        A Distributed Computing System (DCS) is a collection of autonomous computers
interconnected through a communication network to achieve business functions.
Technically, the computers do not share main memory so that the information cannot be
transferred through global variables. The information (knowledge) between the
computers is exchanged only through messages over a network.




------------------------------------------------------------------------------------------------------- 16
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
The restriction of no shared memory and information exchange through messages is of
key importance because it distinguishes between DCS and shared memory multiprocessor
computing systems. This definition requires that the DCS computers are connected
through a network that is responsible for the information exchange between computers.
The definition also requires that the computers have to work together and cooperate with
each other to satisfy enterprise needs Distributed computing can be achieved through one
or more of the following:

                 1. File transfer model

                 2. Client/server model

                 3. Peer-to-peer model

File transfer model is one of the oldest models to achieve distributed computing at a very
minimal level. Basically, programs at different computers communicate with each other
by using file transfer. In fact, e-mail is a special case of file transfer. Although this is a
very old and extremely limited model of distributed computing, it is still used to support
loosely coupled distributed computers. For example, media clips, news items, and
portions of corporate databases are typically exchanged between remote computers
through file transfers; and e-mail is used frequently to exchange files through embeddings
and attachments.

The C/S model is state of the market and state of the practice for distributed computing at
the time of this writing. C/S model, as stated previously, allows application processes at
different sites to interactively exchange messages and is thus a significant improvement
over the file transfer model. Initial versions of C/S model utilized the remote procedure
call paradigm that extends the scope of a local procedure call. At present, the C/S model
is increasingly utilizing the distributed objects paradigm that extends the scope of local
object paradigm (i.e., the application processes at different sites are viewed as distributed
objects).

Peer-to-peer model allows the processes at different sites to invoke each other. The basic
difference between C/S and peer-to-peer is that in a peer-to-peer model the interacting
processes can be a client, server, or both while in a C/S model one process assumes the
role of a service provider while the other assumes the role of a service consumer. Peer-to-
peer middleware is used to build peer-to-peer distributed applications.




------------------------------------------------------------------------------------------------------- 17
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                       User Interface

       A Graphical user interface(GUI) is a method of interacting with a computer that
uses graphical images and widgts in addition to text, such as windows, menus, buttons,
radio boxes, and icons, or employs a pointing device, such as mouse trackball, or
touchscreen in addition to a keyboard.

The standard Java packages, java.awt and javax.swing, together contain a collection of
classes that implement a wide assortment of GUI elements.

Java programs that use Swing use a delegation even model, involving event sources and
even listeners. The sources are components such as Jbutton and JtextField. The listeners
implements one or more interfaces, which includes methods that are called when
particular events occur in the component. Once a listener has been added to a component,
the event delegation model calls the method in the listener when the event occurs. For
example, JButton objects are the source of AcitonEvent objects. By adding an
ActionListener to a JButton object, wheever the button is pressed the actionPerformed()
method of the ActionListener is called automatically, passing it an ActionEvent object


On starting the application the user is asked to enter his name (start screen)




A small dialog box gets opened, When the user enters his name and server name clicks
“Login” button, the data is sent to the server via the socket at port number 9999 and
checks whether the user is already existing or not. If the user already exists then the
server sends the Boolean value “NO” with the variable status data to the client via the
socket of port number 9999. If the user is a new user then a value “YES” is sent to the



------------------------------------------------------------------------------------------------------- 18
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
client and the chatting room frame gets opened where the client can start chatting with the
already logged in users.




The users list will be displayed when u click the “GetUsers” button. The users data is
retrieved from the server via the socket.




Now you can select the name with which u are interested to chat with. There is a textfield
where u can type a message and click “Send” button, when u click the send button the
message and username is sent to the server and the corresponding user gets the message
from the server.


------------------------------------------------------------------------------------------------------- 19
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
There are two options to interact with the users. One is Public option and the other is
Private option. Public means all the users messages will be displayed in the Public
TextArea where the message sent by us will be viewed by every one, and Private means
the data is kept between the two users only




------------------------------------------------------------------------------------------------------- 20
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
If you want to logout just click on the logout button the user name will removed from
current users box.




------------------------------------------------------------------------------------------------------- 21
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                             Design of the application

The application is designed using the following classes.

Here we have one chat package is there all compiled files(classes) all are stored in this
package.

Server.java

The Server just waits listening to the socket for a client to make a connection request.
The server class receives messages form the clients and broadcast messages, starting the
server means a main thread will be created and whenever a new user enters new thread
will be created.
It uses the Hashtable object to keep users list.


LoginDialog.java

The LoginDialog class if for authentication, here when you enter users login method is
called form HandleMessages class to check whether user is a existing one or new user, if
the use is a new user it will start new thread


TestClient.java

The TestClient class initiates a interface window the window includes following
components that is message, private, public, user list boxes and privatemsg, pubicmsg,
getusers, logout buttions.

Receiving messages form server and put into public or pivate messages boxes
accordingly, this is done by using Message class.




------------------------------------------------------------------------------------------------------- 22
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                Testing & Limitations
As Client is running on the Server platform, we hereby only test Client software.

    1) Logon Testing

                                   Problem scenarios:

             Contents                  Input Data                   Input Property
             Server                     H1                          Illegal      value:
                                                                    Wrong IP address
                                        H2                          Legal value: Right
                                                                    IP address
                                         H3                         Empty String

             Username                  Username1                    Illegal value: It is
                                                                    already in the Users
                                                                    list
                                       Username2                    Legal         value:
                                                                    Empty string
                                       Username3                    Legal value: New
                                                                    user name

                                             Testing

             Input Data                Expected Output            Observed Output

             Username1          ,H1 Error message                 Error:
                                                                  java.io.EOFException

             Username2,          H2 Empty string is it will look like
                                    added to users list        “<>”
             Username3,          H3 New user name is it         will    look
                                    added to users list like”<username3>”




------------------------------------------------------------------------------------------------------- 23
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
2) Sending Message & Receiving Message Testing


     Contents                    Input            Input Property
                                 Data

                                 Message1         Enter empty string or string message
                                                  and click on the private msg.

                                 Message2         Enter empty string and select user click
                                                  on the private msg.

      Message                    Message3         Enter empty string and click on the
                                                  public msg.

                                 Message4         Enter string message and select user
                                                  click on the private msg.

                                 Message5         Enter string message and click on the
                                                  public msg.



                                            Testing

Input Data                      Expected                        Observed

Message1                        Error                             Error:
                                                                  java.lang.NullPointerExcep
                                                                  tion
                                                                  Disconnected
Message2                         The selected user gets a “<username>                              “
                                 empty message from the appears on the private
                                 sender          on         the message box
                                 privatemsg.
Message3                         All online users get a “<username>                                “
                                 empty message from the appears on the public
                                 sender on the public message box
                                 message box
Message 4                        The selected user get a “<username> hi how r u
                                 message from the sender “ appears on the private
                                 on the private message message box
                                 box
    Message5                     online users get a empty “<username>                    hi this is
                                 message from the sender new user                        “ appears
------------------------------------------------------------------------------------------------------- 24
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                on the public message on the public message box
                                box



3) Logout Testing

                                        Problem scenarios:

Contents                                            Input property


Logout button                                       Press logout button
                                                    Close client window




Testing

Expected                                            0bserved output

When user presses the logout button, the Client window will be closed
username will be removed from the
userslist.

When user closes the window, the
username will be removed from the users Client window will be closed
list.


Limitations of the design

    1. This Application supports only plain text

    2. When a user logouts the username will be removed from user list still you can
    see the user name till you click getuser button.

    3. When user sends private to message to another user, he will get the message but
       the user who has sended message he won’t get the message.




------------------------------------------------------------------------------------------------------- 25
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                      UML Diagrams

1. LoginDialog.java




------------------------------------------------------------------------------------------------------- 26
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
2. HandleMessages.java




------------------------------------------------------------------------------------------------------- 27
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
3. Message.java




4. Server.java




------------------------------------------------------------------------------------------------------- 28
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
5. TestClient.java



                                                            Java.lang

                                                                 object




                                                          chat

                                                                                                          chat
  chat                                                                    TestClient
                                                                                                              Message
  TestClient_PublicB_actionAdapter
                                                                                                          TestClient_PublicB_actionAdapter
  TestClient_GetUsers_actionAdapter
                                                                        F:Jframe                          TestClient_GetUsers_actionAdapter
    TestClient_Send_actionAdapter
                                                                   GetUsers:Jbutton
                                                                    Logout:Jbutton                          TestClient_Send_actionAdapter
   TestClient_Logout_actionAdapter
                                                                   MessageL:Label
                                                                                                           TestClient_Logout_actionAdapter
  TestClient_PrivateB_actionAdapter                              MessageTF:TextField
                                                                     PrivateL:Label                       TestClient_PrivateB_actionAdapter
                                                                  PrivateTA:TextArea
 Java.awt                                                           PublicB:Jbutton
                                                                     PublicL:Label                Java.awt
                                                                  PublicTA:TextArea
                                                                     Send:Jbutton
    Label         List          TestArea      TestField               Soc:Socket                       Container       Component      Dimension
                                                                      User:String
                                                                     UsersList:List
                 Java.lang                                                                             Font      LayoutManager          Rectangle
                                                                   UsersListl:Label
                                                                        V:vector
                    String

                                                                                               Java.awt.event
                  Java.net

                    Socket

                                                                                                   ActionEvent         ActionListener


                                                                                             Java.io
                 Java.util

                    Vector
                                                                                              ObjectOutputStream           OutputStream
                                                                  setMessages():void
                                                                  setMessages():void
                                                                    setUsers():void
                                                                TestClient()TestClient        Java.lang
                  Javax.swing                              GetUsers_actionPerformed():void
                                                                      Jblnit():void
                                                            Logout_actionPerformed():void
                                                           PrivateB_actionPerformed():void
                                                                                                Exception        StringBuffer      System
                                                           PrivateB_actionPerformed():void
                    JButton          JFrame
                                                             Send_actionPerformed():void
                                                                                                  Java.util



                                                                                                          Collection        Rerator




------------------------------------------------------------------------------------------------------- 29
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                         Source Code

******************************************************************
Server.java

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

public class Server implements Runnable
{
        Message m;
        String username;
        Set set;
        Socket sock;
        int id;
        ObjectOutputStream oos;
        ObjectInputStream ois,ois1;
        static Hashtable clients=new Hashtable();

  Server(Socket s,int i)
      {
             sock=s;
             id=i;
      }

         public static void main(String arg[])
         {
                 int port=9999;
       int count=0;
       try
                  {

        // Starting the Server at port 9999

       ServerSocket ss=new ServerSocket(port);
       System.out.println("Waiting on port : "+port);
       while(true)
                         {

        // Waiting for the Client to start Chatting

------------------------------------------------------------------------------------------------------- 30
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
        Socket sock=ss.accept();
               System.out.println("Connect ID = "+ ++count);

        // Starting the Server Constructor with the Count increment
        // and starting one Thread

       Server s=new Server(sock,count);
       Thread t=new Thread(s);
       t.start();
           }
       }
       catch(Exception e)
                  {
       System.out.println("Server error...");
       System.out.println(e);
       }
   }

   public void run()
        {
      try
                {

        // Reading the Username from LoginDialog

        InputStream is=sock.getInputStream();
               ois=new ObjectInputStream(is);
               username=(String)ois.readObject();

        // Usernames are stored in the Hashtable

                 set=clients.keySet();
                 String status="yes";

        //Checking the user whether he is existing in Hashtable or                       not

                if (set.contains(username))
                                {
                                        status="no";
                                }
                                else
                             {
                                        clients.put(username,sock);
                                }
        // Writing Status to the Client
------------------------------------------------------------------------------------------------------- 31
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                 oos=new ObjectOutputStream(sock.getOutputStream());
                             oos.writeObject(status);
                             while(true)
                                     {

        // Reading data from Message class regarding which button has
           clicked

                          ois1=new ObjectInputStream(is);
                          Message m=(Message)ois1.readObject();
                           if (m.getToAddress().equals("GetUsers"))
                             {
                                  m.setInfo("UsersList");

                                   m.setList(new HashSet(clients.keySet()));

        // Writing Users List to the client

                          oos=new ObjectOutputStream(sock.getOutputStream());
                                oos.writeObject(m);
                                }
                                else if (m.getToAddress().equals("Public"))
                                               {

// Public button has clicked n executing sendMessages method
                                                      sendMessages(m);
                                              }
                                              else
                                              {
                                                              sendMessage(m);
                                              }
                                       }
                         }
                                catch(Exception e)
                                   {
                                         System.out.println(e);
                                   }
                                finally
                                       {
                          System.out.println("Disconnect! ID = "+id);
                                 try
                                   {

// If any error occurs then socket gets closed and
------------------------------------------------------------------------------------------------------- 32
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
// you need to start the server again and the username is removed

// from the Hashtable...so the user needs to be login again


                sock.close();
                    }
                    catch(IOException ie)
                                 {
                                              System.out.println(ie);
                                     }
                   }
            }

                  synchronized void sendMessage(Message m)throws Exception
                  {

        // This method is executed when u want to send Private                            Messages

                          String to=m.getToAddress();
                          Socket s=(Socket)clients.get(to);


        // Writing Message class to the client which includes the text and socket


              ObjectOutputStream oos=new
        ObjectOutputStream(s.getOutputStream());
              oos.writeObject(m);
              }

                  synchronized void sendMessages(Message m)throws Exception
                  {

        // This method is executed when u want to send Public                  Messages
        // The Message shud be sent to all the users...so the users             are retrieved
        // from the Hashtable and for every user the data is sent

                          m.setInfo("Public");
                          int size = clients.size();
                          Collection c = clients.keySet();
                          Iterator it=c.iterator();
                          while (it.hasNext())
                          {
                                   String to = (String)it.next();
------------------------------------------------------------------------------------------------------- 33
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                              Socket s=(Socket)clients.get(to);
        // Writing Message class for every user


                          ObjectOutputStream oos=new ObjectOutputStream
                                        (s.getOutputStream());
                          oos.writeObject(m);
                          }
                 }
}

******************************************************************
LoginDialog.java
******************************************************************
package chat;
import chat.HandleMessages;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class LoginDialog extends JDialog
        {
         //String host="localhost";
          int port=9999;
          JPanel panel1 = new JPanel();

          Label label1 = new Label();
          Label label2= new Label();
          JTextField username = new JTextField();
          JTextField servername = new JTextField();
          JButton button1 = new JButton();

        public static void main(String s[])
         {
                LoginDialog ld=new LoginDialog(new JFrame());
                ld.setLocation(250,250);
                ld.setSize(450,350);
                ld.setVisible(true);
         }

    public LoginDialog(JFrame frame, String title, boolean modal)
         {

        // This Constructor is called and the Dialog box appears
------------------------------------------------------------------------------------------------------- 34
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                 super(frame, title, modal);
                 try

                 {
                            jbInit();

                            getContentPane().add(panel1);
                 }
                 catch(Exception ex)
                 {
                   ex.printStackTrace();
                 }
        }

      public LoginDialog(JFrame frame)
               {
                      this(frame,"Login Dialog", false);
                }

        public LoginDialog(JFrame frame, boolean modal)
         {

        // Second this constructor is called

                     this(frame,"Login Dialog", modal);
         }


         public LoginDialog(JFrame frame, String title)
          {

                 // First this constructor is called

                     this(frame, title, false);
            }

                  private void jbInit() throws Exception
         {

        // Adding all the components to the Dialog Box for the user                to
                                                                               Authenticate
                 label2.setAlignment(Label.LEFT);
                 label2.setFont(new java.awt.Font("Dialog",0,20));
                 label2.setText("ServerName");
                 label2.setBounds(new Rectangle(25, 45, 127, 32));
------------------------------------------------------------------------------------------------------- 35
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                 panel1.setLocale(java.util.Locale.getDefault());
                 panel1.setLayout(null);
                 servername.setText("");

                 servername.setBounds(new Rectangle(173, 45, 156, 20));
                 label1.setAlignment(Label.CENTER);
                 label1.setFont(new java.awt.Font("Dialog", 0, 18));
                 label1.setText("UserName");

                 label1.setBounds(new Rectangle(25, 125, 127, 32));
                 panel1.setLocale(java.util.Locale.getDefault());
                 panel1.setLayout(null);
                 username.setText("");
                 username.setBounds(new Rectangle(173, 130, 156, 20));
                 button1.setLabel("Login");
                 button1.setBounds(new Rectangle(150, 176, 121, 34));
                 button1.addActionListener(new
                               LoginDialog_button1_actionAdapter(this));
                 panel1.add(label1, null);
                 panel1.add(label2, null);
                 panel1.add(username, null);
                 panel1.add(servername, null);
                 panel1.add(button1, null);
        }

        protected void processWindowEvent(WindowEvent e)
        {

               if (e.getID() == WindowEvent.WINDOW_CLOSING)
               {
        cancel();
               }
               super.processWindowEvent(e);
         }

         void cancel()
        {
                dispose();
        }

        void button1_actionPerformed(ActionEvent e)
          {

        // Login Button is clicked after the user enters his name
        // and forward to the HandleMessages Class
------------------------------------------------------------------------------------------------------- 36
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
         HandleMessages hm=new HandleMessages();
          try
         {


         // Login method is called from HandleMessages class to check whether
         // user is a existing one or a new user

         if (hm.login(username.getText(), servername.getText(), port))
         {

         // if user is a new user then the below statements r executed

         hm.start();
         new Thread(hm,"read").start();
         setVisible(false);
         return;
                  }
          }
          catch(Exception e1)
                 {
                         e1.printStackTrace();
                 }
     }
         }

         class LoginDialog_button1_actionAdapter implements

         java.awt.event.ActionListener
         {
          LoginDialog adaptee;

          LoginDialog_button1_actionAdapter(LoginDialog adaptee)
                  {
                         this.adaptee = adaptee;
                  }
          public void actionPerformed(ActionEvent e)
                 {
                         adaptee.button1_actionPerformed(e);
                 }
         }




------------------------------------------------------------------------------------------------------- 37
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
******************************************************************
TestClients.java
******************************************************************

package chat;
import chat.Message;
import java.awt.*;

import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;

public class TestClients
        {

                   Socket soc;
                   String user;
                   Vector v;
                   JFrame f = new JFrame("Chat Room");
                   Label PrivateL = new Label();
                   TextArea PrivateTA = new TextArea();
                   Label PublicL = new Label();
                   TextArea PublicTA = new TextArea();
                   TextField MessageTF = new TextField();
                   JButton PrivateB = new JButton();
                   JButton PublicB = new JButton();
                   JButton GetUsers = new JButton();
                   JButton Logout = new JButton();

                   java.awt.List UsersList = new java.awt.List();
                   Label MessageL = new Label();
                   JButton Send = new JButton();
                   Label UsersListL = new Label();

     public TestClients(Socket soc,String user)
                {

        // TestClients constructor will be called with two                       parameters as
        // socket and the user name
                  this.soc=soc;
                  this.user=user;
                           try
------------------------------------------------------------------------------------------------------- 38
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                           {
                                  jbInit();
                          }
                    catch(Exception ex)
                          {
                          ex.printStackTrace();
                           }
                   }


         void jbInit() throws Exception
                  {

          // Adding the componenets to the Frame

                   PrivateL.setFont(new java.awt.Font("Dialog", 1, 15));
                   PrivateL.setText("Private Message Box");
                   PrivateL.setBounds(new Rectangle(8, 28, 377, 15));
                   f.getContentPane().setLayout(null);
                   PrivateTA.setText("");
                   PrivateTA.setBounds(new Rectangle(7, 49, 551, 114));
                   PublicL.setFont(new java.awt.Font("Dialog", 1, 15));
                   PublicL.setText("Public Message Box");
                   PublicL.setBounds(new Rectangle(8, 166, 448, 27));
                   PublicTA.setText("");
                   PublicTA.setBounds(new Rectangle(10, 194, 550, 198));
                   MessageTF.setText("<"+user+"> ");
                   MessageTF.setBounds(new Rectangle(13, 422, 550, 64));
                   PrivateB.setFont(new java.awt.Font("Dialog", 1, 13));
                   PrivateB.setLabel("Private Msg");
                   PrivateB.setBounds(new Rectangle(13, 492, 140, 30));


                   PrivateB.addActionListener(new
                   TestClients_PrivateB_actionAdapter(this));
                   PublicB.setFont(new java.awt.Font("Dialog", 1, 13));
                   PublicB.setLabel("Public Msg");
                   PublicB.setBounds(new Rectangle(158, 492, 132, 32));
                   PublicB.addActionListener(new
                   TestClients_PublicB_actionAdapter(this));
                   GetUsers.setFont(new java.awt.Font("Dialog", 1, 13));
                   GetUsers.setLabel("GetUsers");
                   GetUsers.setBounds(new Rectangle(296, 493, 137, 32));
                   GetUsers.addActionListener(new
                   TestClients_GetUsers_actionAdapter(this));
                   Logout.setFont(new java.awt.Font("Dialog", 1, 13));
------------------------------------------------------------------------------------------------------- 39
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                   Logout.setLabel("Logout");
                   Logout.setBounds(new Rectangle(437, 493, 125, 32));
                   Logout.addActionListener(new
                   TestClients_Logout_actionAdapter(this));
                   UsersList.setBounds(new Rectangle(562, 49, 101, 343));
                   MessageL.setFont(new java.awt.Font("Dialog", 1, 15));
                   MessageL.setText("Message ");
                   MessageL.setBounds(new Rectangle(13, 392, 91, 26));

                   Send.setFont(new java.awt.Font("Dialog", 1, 16));
                   Send.setLabel("Send");
                   Send.setBounds(new Rectangle(574, 422, 94, 65));
                   Send.addActionListener(new
                  TestClients_Send_actionAdapter(this));
                  UsersListL.setFont(new java.awt.Font("Dialog", 1, 15));
                  UsersListL.setText("Current Users");
                  UsersListL.setBounds(new Rectangle(561, 29, 111, 18));
                  f.getContentPane().add(UsersList, null);
                  f.getContentPane().add(MessageTF, null);
                  f.getContentPane().add(PublicTA, null);
                  f.getContentPane().add(MessageL, null);
                  f.getContentPane().add(Send, null);
                  f.getContentPane().add(PrivateB, null);
                  f.getContentPane().add(PublicB, null);
                  f.getContentPane().add(GetUsers, null);
                  f.getContentPane().add(Logout, null);
                  f.getContentPane().add(PublicL, null);
                  f.getContentPane().add(PrivateTA, null);
                  f.getContentPane().add(PrivateL, null);
                  f.getContentPane().add(UsersListL, null);
                  f.setSize(new Dimension(700, 550));
                  f.setVisible(true);

}

         public void setUsers(Collection c)
                 {

                 // Writing the UserNames from Server to the Component

                                  UsersList.removeAll();
                                  Iterator i=c.iterator();
                          while (i.hasNext())
                                  {
                                          String s = (String)i.next();
------------------------------------------------------------------------------------------------------- 40
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                          if (s==user)
                                      {
                 System.out.println("Removing the current user");
                                            UsersList.add("");
                                      }
                                      else
                                      UsersList.add(s);
                               }
      }

          public void setMessage(String s)
                 {

     // Writing the Message sent by the user from Server to the                         Component

                                    PrivateTA.append(s+"\n");
                  }

           public void setMessages(String s)
                 {

      // Writing the Message sent by the user from Server to                              the
Component

                                     PublicTA.append(s+"\n");
                  }

      void Logout_actionPerformed(ActionEvent e)
               {

     // Logout button is clicked and the Frame gets Closed


                   System.exit(0);
      }

          void GetUsers_actionPerformed(ActionEvent e)
      {

     // GetUsers button is clicked

                          try
                          {

     // Writing the String through the Message class to the                        Server
------------------------------------------------------------------------------------------------------- 41
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
      ObjectOutputStream oos=new
        ObjectOutputStream(soc.getOutputStream());
               oos.writeObject(new Message("GetUsers", " "));
                      }
                       catch(Exception e1)
                        {
              e1.printStackTrace();
                        }
      }

                 void PublicB_actionPerformed(ActionEvent e)
                  {
                                try
                                      {

    // Writing the string through the Message class to the                        Server

         ObjectOutputStream oos=new
        ObjectOutputStream(soc.getOutputStream());
      oos.writeObject(new            Message("Public",MessageTF.getText()));
                         MessageTF.setText("<"+user+"> ");
                                     }
               catch(Exception e1)
                       {
                             e1.printStackTrace();
                       }
                }

         void PrivateB_actionPerformed(ActionEvent e)
                 {
                       try

                     {
               ObjectOutputStream                                                              oos=new
        ObjectOutputStream(soc.getOutputStream());
               oos.writeObject(new
        Message(UsersList.getSelectedItem(),MessageTF.getText()));
               MessageTF.setText("<"+user+"> ");
                      }
                       catch(Exception e1)
                       {
                             e1.printStackTrace();
                       }
               }
------------------------------------------------------------------------------------------------------- 42
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
             void Send_actionPerformed(ActionEvent e)
                     {
                             try
                           {

             // Writing the username through the Message class to the                            Server

 ObjectOutputStream oos=new
      ObjectOutputStream(soc.getOutputStream());


                          oos.writeObject(new
             Message(UsersList.getSelectedItem(),MessageTF.getText()));
                    MessageTF.setText("<"+user+"> ");
                           }
                           catch(Exception e1)
                           {

                          e1.printStackTrace();
                            }
              }
     }

       class                TestClients_Logout_actionAdapter                                implements
java.awt.event.ActionListener
    {
               TestClients adaptee;

                    TestClients_Logout_actionAdapter(TestClients adaptee)
              {
                     this.adaptee = adaptee;
         }
             public void actionPerformed(ActionEvent e)

      {
  adaptee.Logout_actionPerformed(e);
        }
    }

       class              TestClients_GetUsers_actionAdapter                                implements
java.awt.event.ActionListener
    {
               TestClients adaptee;

------------------------------------------------------------------------------------------------------- 43
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                  TestClients_GetUsers_actionAdapter(TestClients adaptee)
                  {
     this.adaptee = adaptee;
    }
    public void actionPerformed(ActionEvent e)
    {
      adaptee.GetUsers_actionPerformed(e);
    }
}

class TestClients_PublicB_actionAdapter implements java.awt.event.ActionListener
{

    TestClients adaptee;

    TestClients_PublicB_actionAdapter(TestClients adaptee)
    {
      this.adaptee = adaptee;
    }
    public void actionPerformed(ActionEvent e)
    {
      adaptee.PublicB_actionPerformed(e);
    }
}

class TestClients_PrivateB_actionAdapter implements java.awt.event.ActionListener
     {
       TestClients adaptee;

           TestClients_PrivateB_actionAdapter(TestClients adaptee)
                           {
                            this.adaptee = adaptee;
                            }
                      public void actionPerformed(ActionEvent e)
           {

                                    adaptee.PrivateB_actionPerformed(e);
           }
       }

class TestClients_Send_actionAdapter implements java.awt.event.ActionListener
     {
               TestClients adaptee;

           TestClients_Send_actionAdapter(TestClients adaptee)
------------------------------------------------------------------------------------------------------- 44
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                            {
                             this.adaptee = adaptee;
                             }
                      public void actionPerformed(ActionEvent e)
          {
                             adaptee.Send_actionPerformed(e);
                             }
      }




HandleMessages.java
************************************************************************
package chat;
import chat.TestClients;
import chat.Message;
import java.net.*;
import java.io.*;

public class HandleMessages implements Runnable
        {
          Socket s;
          String host,user;
          int port;
          TestClients tc;

  public HandleMessages() { }

  public void start()
  {
       // When start method is called then TestClients with two                parameters will be
                                                                                               called

              tc=new TestClients(s,user,host);
  }

  public void readMessage()throws Exception


  {

       // Reading data from the Server to which method to be
executed for the
       // button which user has clicked
------------------------------------------------------------------------------------------------------- 45
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
           ObjectInputStream ois=new
        ObjectInputStream(s.getInputStream());
   Message m=(Message)ois.readObject();
   String info=m.getInfo();
   if ("UsersList".equals(info))
   {

        // setUsers method is called when user clicks the GetUsers                        button


       tc.setUsers(m.getList());
   }
         if ("Public".equals(info))
         {



// setMessages method is called when user clicks the Public button
               tc.setMessages(m.getMessage());
         }
    else
    {

        // setMessage method is called when user clicks the Private              button

                  tc.setMessage(m.getMessage());
                  }
         }

         public void run()
         {
        try
         {
         while(true)
        {
                        readMessage();
         }

        }
   catch(Exception e)
   {

        // If any error occurs with the server then the server should            be started again

------------------------------------------------------------------------------------------------------- 46
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
            System.out.println("Problem with Connection to Server");
             System.out.println("PLZ Start the Server again");
                   }
            }

    public boolean login(String username,String servername,int port)throws Exception
    {

        // To send the user name to the Server and check whether the                      username is
Exisiting in Hashtable or not

        s= new Socket(servername, port);

            // Writing the user name to the server

            ObjectOutputStream oos = new
            ObjectOutputStream(s.getOutputStream());
            oos.writeObject(username);
            user=username;
            // writing the host name to the server


            // Retrieved the status from Server whether the user is                       existing     or
not

        ObjectInputStream ois = new        ObjectInputStream(s.getInputStream());
        String status = (String) ois.readObject();
             if (status.equals("no"))
         return false;
        else
         return true;
    }
}

Message.java
************************************************************************
package chat;


public class Message implements java.io.Serializable
{
        private String to,mess,info="";

                   public Message(String sa,String s2)
                          {
------------------------------------------------------------------------------------------------------- 47
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                                   to=sa;
                                    mess=s2;
                          }

                 public void setToAddress(String s)
                         {
                                to=s;
                         }

                 public void setMessage(String s)
                         {
                                mess=s;
                         }

                 public String getToAddress()
                        {
                                return to;
                        }

                 public String getMessage()
                        {
                                return mess;
                        }

                 public void setInfo(String s)
                    {
                                info=s;
                         }

                 public String getInfo()
                    {
                                return info;
                        }

                 public void setList(java.util.Collection s)
                    {
                                set=s;
                         }


                public java.util.Collection getList()
                        {
                                return set;
                        }
        private java.util.Collection set; }
------------------------------------------------------------------------------------------------------- 48
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                   Conclusion & Further Development

        In this project, we have created a simple chat room where different clients can
communicate on network.(client-server model) where client can send message publicly or
privately.

This application can be used in small organizations, but code should be modified to make
the program efficient and secure.

If we have more time, we can develop this application to supports the user may be allowed to
change the size and font of the display in the message box and we can our program to support
popup windows so that private chat is shown individually.

It will also be possible to make it a closed chat i.e. restrict the chat to a specific set of
users rather than make it open to anybody in the network.

In addition we can voice chat and sharing files on network.




------------------------------------------------------------------------------------------------------- 49
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha
                          Reference Material


1. The JavaTM Tutorial

2. Java By Dissection --author: Ira Pohl/ Charlie McDowell

3. The Complete Reference Java2 --Tata McGraw Hill

4. Internet Networking Handbook --author: McGraw Hell

5. www.java.sun.com

6. Course Handout etc.




------------------------------------------------------------------------------------------------------- 50
Participants: Eswar Emmadi                                    Supervisor: Dan Witzner Hansen
                Suresh Kumar Dontha

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:10/22/2011
language:English
pages:50