P2P Chat Server System

65
Chat Server System Report submitted in partial fulfillment of the requirement for the degree of B.Tech In Computer Science & Engineering Under the Supervision of Sudhir Tyagi By Harshul Madan To Maharaja Agrasen Institute of Technology 1

Transcript of P2P Chat Server System

Page 1: P2P Chat Server System

 Chat Server System 

 Report submitted in partial fulfillment of the

requirement for the degree of  B.Tech

In

Computer Science & Engineering

Under the Supervision ofSudhir Tyagi

ByHarshul Madan

To Maharaja Agrasen Institute of Technology

Guru Gobind Singh Indraprastha UniversityKashmere Gate, Delhi-06

 September 2011

1

Page 2: P2P Chat Server System

Acknowledgment

I have taken efforts in this project. However, it would not have been possible without the kind support and help of many individuals and organizations. I would like to extend my sincere thanks to all of them.

I am highly indebted to Mr. Sudhir Tyagi & Mr. Rajeev Sharma for his guidance and constant supervision as well as for providing necessary information regarding the project & also for their support in completing the project.

I would like to express my gratitude towards my parents & members of Siemens IT Solutions & Services Pvt. Ltd for their kind co-operation and encouragement which help me in completion of this project.

I would like to express my special gratitude and thanks to industry persons for giving me such attention and time.

My thanks and appreciations also go to my colleagues in developing the project and people who have willingly helped me out with their abilities.

2

Page 3: P2P Chat Server System

Abstract

A chat application allows users to communicate with others via texting, messaging, video

and audio conferencing. While developing a web application web masters always think

that they should communicate with their audience directly rather than emails, phone or

contact forms, or chat applications can be used in various web applications such as social

networking sites, business sites for live support etc.

In today’s world, technology is undergoing through fast changes. For the sake of

accuracy and speed, computers is being introduced everywhere. Most of the present day

Chat Server are equipped with many sophisticated features, but still a lot of gaps remain

in field of efficiency. These systems require a great amount of physical memory for work

to be carried out and also involve consideration for lack of adequate security.

The chat server is responsible for providing a mechanism for the clients to communicate.

This includes allowing clients to login so they can be identified by username and sending

messages from one client destined to another. This also includes listing the usernames of

the clients that are currently logged in to facilitate communication.

The project for Chat Server System, being submitted has been developed in well known

Java language. This requires a less amount of memory & other resources when run. It

delivers a high degree of accuracy. It is superior in performance, extremely fast in

operation and very easy to use.

3

Page 4: P2P Chat Server System

TABLE OF CONTENTS

Part 1:Introduction………………………………………………………………..

Part 2: Architecture…………………………………………………………….....

2.1 Software Requirement Specification…………………………………...

2.2 Dataflow Diagram……………………………………………………….

2.3 Use Case Diagram……………………………………………………….

2.4 Activity Diagram………………………………………………………...

2.5 Sequential Diagram……………………………………………………..

2.6 Entity-Relationship Diagram…………………………………………..

Part 3: Theory of Operation……………………………………………………..

Part 4: Related theory……………………………………………………………

Part 5: Testing……………………………………………………………………..

Part 6: Screenshots……………………………………………………………….

Part 7: Future Perspective………………………………………………………..

Part 8: Conclusion………………………………………………………………...

Part 9:Biblography………………………………………………………………..

Appendix A: User Manual

Appendix B: Source Code

4

Page 5: P2P Chat Server System

Part 1: IntroductionChat server is a standalone application that is made up the combination of two-application, server application (which runs on server side) and client application (which runs on client side). This application is using for chatting in LAN. To start chat you must be connected with the server after that your message can be broadcast to each and every client.    It is Intranet Communication Software intended for sending and receiving messages between the members logged in the intranet. The Chat server can be configured to listen at a particular port specified by the system administrator. The Chat clients have to register themselves with a username and password. The entire implementation of the Chat Server includes the following modules:

• The Chat Server: This module is the core of the entire implementation. The server program will listen at a particular port that is configured by the system administrator. Once a client tries to connect to the Chat Server with his/her username and password, the chat server checks for the validity of the user credentials and if the validation succeeds, the client connection is allowed, else discarded. Once the client is connected, his/her username is included in the list of logged in clients. When the server receives a message from a client, it checks the data for the destination user and transmits it to the corresponding user.

• The Administrative tool: This tool allows starting and stopping the chat server, configuring on which port the server should wait for the client connections, set user permissions etc. After registration, the user can select the person and the can start private / public sessions.

For making this application we are using some core java features like swing, collection, networking, I/O Streams and threading also. In this application we have one server and any number of clients (which are to be communicated with each other).

Part 2: Architecture

2.1 Software Requirement SpecificationA Software Requirements Specification (SRS) – a requirements specification for a software system – is a complete description of the behavior of a system to be developed. It includes a set of use cases that describe all the interactions the users will have with the software. In addition to use cases, the SRS also contains non-functional (or Gapor Dison's method) requirements. Non-functional requirements are requirements, which impose

5

Page 6: P2P Chat Server System

constraints on the design or implementation (such as performance engineering requirements, quality standards, or design constraints).

1. IntroductionThis document aims at defining the overall software requirements for “Chat Server”. Efforts have been made to define the requirements exhaustively and accurately. The final product will be having only features/functionalities mentioned in this document and assumptions for any additional functionality/feature should not be made by any of the parties involved in developing/testing/implementing/using this product. In case it is required to have some additional features, a formal change request will need to be raised and subsequently a new release of this document and/or product will be produced.

1.1Purpose:This specification document describes the capabilities that will be provided by the software application “Chat Server”. It also states the various required constraints by which the system will abide. The intended audiences for this document are the development team, testing team and end users of the product.

1.2 Scope:This is commonly seen in schools and businesses around the world and can be used quickly and efficiently for simple communication through message passing. It employs user-friendly interface for convenient user interaction.

1.4 Definitions:a) Send

For sending the message from source to the destinationb) Leave chat

Disconnect the clientc) Join

Connects client to serverd) Quit

Closes the client interface

1.3 References:a) Java 7 The Complete Reference by Herbert Schildtb) Head First Java –O’Reillyc) Black Book –Dr. R. Nageswara Rao

2. OverviewThe rest of this SRS document describes the various system requirements, interfaces, features and functionalities in detail.

6

Page 7: P2P Chat Server System

2.1 Overall Description:The purpose of this application is to implement message passing between clients and server. It enables connecting multiple clients to a single server and deploys message passing between them.

a) Client and Server are connected.b) Message passing occurs between the server and client.c) Multiple clients may also be connected.

2.2 Product Perspective: Chat Server is an application to communicate and exchange information. It offers a chat system for one-on-one communication or many-on-many communication. Its primary goals are simplicity, comfort, stability and free information exchange. Chat Server fits well as private chat for friends, as a community chat system and for business support.

2.3 User Interface:a) Status dialog with chat activity and usernameb) Option to leave chat anytime.c) Option to send private and public message.

2.4 Hardware Interface:a) Client Side

(1) Processor: Pentium II at 500 MHz (2) Ram: 64 MB(3) Disk Space: 2 MB

b) Server Side(1) Processor: Pentium III at 1 GHz (2) Ram: 512 MB(3) Disk Space: 3 MB

2.5 Communication Interfaces:a) Client on Internet will be using UDP Protocol.b) Client on intranet will be using UDP protocol

2.6 Operating Environment: The OS types are:

a) Windows NTb) Windows XP

7

Page 8: P2P Chat Server System

c) Windows 98d) Linux

2.5 Operations:a) Message passing between client and serverb) Communication between multiple clients.

2.6 Product Function:a) The server allows access to multiple clients to send private or public messages

depending upon user discretion.b) A summary of the major functions that the software will perform:c) A login facility for enabling access to the client in the intranet network.d) User will be able to send public and private messages based on his discretion.e) Chat server can be terminated at any time.

2.7 User Characteristics:a) Educational level: The users should be comfortable with English language.b) Experience: should have an experience in handling database systems. c) Technical expertise: Should be comfortable using computer applications as per

the requirements of their role.

2.8 Apportioning of Requirements: Not required.

3 Specific requirementsThis section contains the software requirements to a level of detail sufficient to enable designers to design the system, and testers to test the system.

3.1 External Interface Requirement:

3.1.1 User Requirement:

The following screens will be provided:

Client Interface:

This will be the first screen that will be displayed. It will allow user to send messages based upon the user’s discretion (public/private). Various fields available on this screen will be

(i) User ID: Alphanumeric of length upto 10 characters.

(ii) Machine IP: Port: Will have the following values:

8

Page 9: P2P Chat Server System

o Machine IP o The port through which user can connect to server.

(iii) Message: Alphanumeric of length upto 8 characters.

(iv) Receiver’s User Id: To whom message is to be sent or it can be left blank in order to broadcast the message publicly on all client interface connected to server.

(v) Join: to join chat.

(vi) Dialog Box: shows the chat activity.

(vii) Leave Chat: To disconnect from chat server.

(viii) Quit: to close client interface.

3.1.2 Hardware Interface:

As stated in Section 2.4

3.1.3 Software Interface:

Any windows based operating system. An operating system with LAN connectivity. A computer with free ports.

3.1.4 Communication Interface:

Chat Server and Port need to be present.

3.3 Performance Requirements:

None

3.4 Design Constraints:

None

3.5 Software System Attributes:

Reliable Available Secure

9

Page 10: P2P Chat Server System

3.6 Security:

Users will have to enter correct username, role and password in order to send message.

3.7 Maintainability:

The application will be designed in a maintainable manner. It will be easy to incorporate new requirements in the individual modules.

3.8 Portability:

The application will be easily portable on any windows-based system.

3.9 Logical Database Requirement:

None

3.10 Other Requirements:

None

Part 3 Theory of Operation

The stand-alone Java chat server proxy called "chatserver.java" , will correctly do the following:

Read a local port to set the server running on as a command line argument. Create a socket and accept chat packets on the local port. Create a thread to handle each packet which arrives at the server:

o Parse the packet and decide what to do with it o Send the resulting packet to one client or broadcast to all clients

Close the sockets if an exception occurs. Correctly terminate the threads. After the sockets are closed, connect more clients without re-starting the chat

server. Complete each of these tasks for multiple concurrent users.

Each of these tasks was implemented entirely in Java, and can be run on any machine which supports Java.

Implementation

Read the local port as command line arguments:

10

Page 11: P2P Chat Server System

This was done by parsing the commands entered by the user when the chat server was initially started, picking out the port to operate on. This was checked for legality, and passed to the rest of the program if acceptable. If invalid, the program would exit and report the appropriate error.

Create a socket and accept chat packets on the local port:

This was accomplished by creating a new Datagram Socket. The port which it listens on is the one passed by the user on the command line.

Create a thread to handle each packet which arrives at the server:

This was done by implementing a new Class, chatserverThread which extends the Thread Class, and creating new chatserverThread, which accept a Socket and a Hashtable as its parameters. The Socket that is passed is the DatagramSocket created when the server is started. The Hashtable is the main Hashtable which keeps track of the current users logged onto the server. The Run() method of the Thread Class is overwritten, and does the actual data stream transferring The chat server accepts data on the datagram socket with the use of the recieve() method, and stores it in a buffer.

Parse the packet and decide what to do with it:

There are many methods which look at the packet and test it to see what type of packet it is. If it is a join packet the username is inspected to see if it a valid one. If it is, the user is entered into the HashTable as an active client. Otherwise the user is not entered. If it is a leave packet, the username is checked against the HashTable for validity. If the packet is a message packet, the sender and receiver IDs are checked against the HashTable for validity.

Send the resulting packet to one client or broadcast to all clients:

The server will make each packet with the MakePacket() method. It will then send the packet to one client or all clients, depending on how certain flags were set when the packet was parsed.

Close the sockets if either closes or an exception occurs:

If any type of error is detected while the server is either started or running, it will immediately close all sockets, and terminate, unless it is an error that is not fatal to server, in which case it will remain running, serving more clients.

Correctly terminate the threads:

11

Page 12: P2P Chat Server System

Again, if any type of error is detected while the server is either started or running, it will immediately end all threads, and terminate itself, unless it is an error that is not fatal to server, in which case it will remain running, serving more clients.

After the sockets are closed, connect more clients without re-starting the proxy:

Once the server is started it will continually listen for new connections on the port it is listening to. Therefore, if one connection is ended, thereby closing the sockets and terminating the threads, the chat server will still be active, listening for more users to connect. It does not need to be restarted in order to be connected to by more clients, because it runs independently, with or without users currently using it.

Complete each of these tasks for multiple concurrent users:

Because the server creates a new thread for each client attempting to connect to it, it can support multiple concurrent users simultaneously without any problem

Read the local port as command line arguments:

This was done by parsing the commands entered by the user when the chat server was initially started, picking out the port to operate on. This was checked for legality, and passed to the rest of the program if acceptable. If invalid, the program would exit and report the appropriate error.

Open a User Interface:

This is done by initializing a new userinterfaceframe object when the client is started. This object contained the actual user interface that the user will see.

Parse the user input from the user interface

This is done via various parsing methods which take the fields from the user interface and pick them apart.

Send the packets to the server:

This is done by sending the created packet out on the DatagramSocket created when the user interface is created.

Create a socket and accept chat packets at the client:

This was accomplished by creating a new Datagram Socket to listen on when the client is initialized.

Create a thread to handle each packet which arrives at the client:

12

Page 13: P2P Chat Server System

This was done by implementing a new Class, clientrecieve which extends the Thread Class, and creating new clientrecieve, which accept a Socket and a reference to the User Interface, and a reference the text area of the User Interface as its parameters. The Socket that is passed is the DatagramSocket created when the client is started. The User Interface is the one the client is working with. The text area is the one that the messages will get presented to the user on. The Run() method of the Thread Class is overwritten, and does the parsing of the incoming message.

Parse the packet and decide what to do with it:

If the user has just started the client, the only fields of the User Interface they will have access to are the Machine:Port input and the Username input. When they send a join packet to the server, they will only receive a join confirmation packet is the server can accept their username. In this case the packet coming back to the client will be a join packet as well. The clientrecieve thread checks for this, and updates the status of the User Interface only if this is the case. Otherwise the user is forced to enter another username and try again.

Output the message contained in the packet to the user interface:

The clientrecieve thread will output the message to the text area of the user interface by appending the message to its reference to this

Close the sockets if either closes or an exception occurs:

If any type of error is detected while the client is either started or running, it will immediately close all sockets, and terminate itself, unless it is an error that is not fatal to client, in which case it will remain running, sending and receiving more packets.

Correctly terminate the threads:

After the user has decided to leave the chat, the sockets are closed and the threads are ended

CLASS MODULES

The Chatserver Class

The ChatServer Class implements the Main () method of the chat server. It accepts and parses the users input, while doing some basic error checking. It then creates a new chatserverthread to handle each incoming packet a new hashtable to store the client entries.

13

Page 14: P2P Chat Server System

The ChatServerThread Class

The ChatServerThread Class implements the actual threads which the chatserver Server uses to send and receive data. It starts the actual movement of data on the thread with the use the Run() method of the Thread Class.

The ClientInterface Class

The ClientInterface Class implements the Main () method of theclient. It creates a new userinterfaceframe which is the actual user interface the client will see. It also creates the new clientreceive thread to handle incoming packets.

The ClientInterfaceFrame Class

This Class creates the actual user interface that the user will interact with.

The ClientRecieve Class

This Class handles incoming packets from the server. It listens on the Datagram Socket that is passed to it. When a packet arrives is parses it, and takes the appropriate action. In all cases it appends the message to the text area of the user interface.

The ClientsTableEntry Class

This Class was implemented to create objects to store in the hashtable to represent each active user. These objects contain the username, IP address, and port of each user

Part 4 : Related theory

The Java Technology PhenomenonJava technology is both a programming language and a platform.

The Java Programming LanguageThe Java programming language is a high-level language that can be characterized by all of the following buzzwords:

Simple Object oriented Distributed Multithreaded Dynamic

Architecture neutral Portable High performance Robust Secure

14

Page 15: P2P Chat Server System

Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by thejavac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

An overview of the software development process.

Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

Through the Java VM, the same application is capable of running on multiple platforms.

15

Page 16: P2P Chat Server System

The Java PlatformA platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.The Java platform has two components:

The Java Virtual Machine The Java Application Programming Interface (API)

You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms.The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.

The API and Java Virtual Machine insulate the program from the underlying hardware.

As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.The terms "Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.

The general-purpose, high-level Java programming language is a powerful software platform. Every full implementation of the Java platform gives you the following features:

Development Tools: The development tools provide everything you'll need for compiling, running, monitoring, debugging, and documenting your applications. As a new developer, the main tools you'll be using are the javac compiler, the java launcher, and the javadoc documentation tool.

Application Programming Interface (API): The API provides the core functionality of the Java programming language. It offers a wide array of useful

16

Page 17: P2P Chat Server System

classes ready for use in your own applications. It spans everything from basic objects, to networking and security, to XML generation and database access, and more. The core API is very large; to get an overview of what it contains, consult the Java SE Development Kit 6 (JDK™ 6) documentation.

Deployment Technologies: The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users.

User Interface Toolkits: The Swing and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces (GUIs).

Integration Libraries: Integration libraries such as the Java IDL API, JDBC™ API, Java Naming and Directory Interface™ (JNDI) API, Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote objects.

UDP - User Datagram Protocol

User Datagram Protocol or UDP for short is very simple connectionless protocol that can be used to transfer datagram packets in both the direction. Client can send the datagram packets to server and it can also receive the reply from server. UDP does not provide the reliability nor ordering guarantees that TCP does.

What is UDP?The User Datagram Protocol (UDP) is a transport protocol that supports Network Application. It layered on just below the ‘Session’ and sits above the IP(Internet Protocol) in open system interconnection model (OSI). This protocol is similar to TCP (transmission control protocol) that is used in client/ server programs like videoconference systems expect UDP is connection less.

User Datagram Protocol transports the data between the computers in the form of data packets, but it does not track the data and never shows the confirmation report.

UDP and TCP both are used to transport the data but there are some differences in it.

UDP is a connectionless protocol while TCP is connection oriented. UDP never track the data, so never shows the confirmation report, while TCP

track the data and show confirmation report, after receiving, if the data losses anywhere it resends that particular data.

UDP transport the data in the form of Data packets, whereas TCP transport the data in long stream. It flows continuous. To make in the form of packets stack is

17

Page 18: P2P Chat Server System

required on the both end for reassembling them. In the sending end, stack breaks the flow of the data and sends the data in the form of packets, on the receiving end, the stack reassemble the data from packets to flowing form.

TCP has 20 bytes of overhead while UDP has only 8 bytes of overhead. Times can be established in TCP protocol in sending the data, because the data

packets goes one after one in the sequence form and each packets takes a specific time period, whereas no times period can be established in the UDP protocol case, because the data transmits in non-sequence form.

UDP transmit the data according to the generation of data, which is produced by the bandwidth of the Internet, if there is any obstacle in the network it could be lost due to the overflowing of data in the router. On the other hand TCP has a cognition control mechanism that indicates the senders about the congestion and it tolerate the transmitting process for some times.

IN spite of being so many demerits, UDP is very useful in some circumstances, especially in speed and network management. Its speed is faster than TCP protocol. UDP transports the data periodically and with no guarantee. So the updated data can be send after a certain period, which not only recovers the lost data but also it updates network. While in the TCP it is very difficult to recover the lost data at the congestion stage. It is also not suitable to carry network management due to its transmitting methodology.

UDP Client in JavaThe User Datagram Protocol (UDP) is a transport protocol that supports Network Application. It layered on just below the ‘Session’ and sits above the IP(Internet Protocol) in open system interconnection model (OSI). This protocol is similar to TCP (transmission control protocol) that is used in client/ server programs like videoconference systems expect UDP is connection less.

User Datagram Protocol transports the data between the computers in the form of data packets, but it does not track the data and never shows the confirmation report.

UDP and TCP both are used to transport the data but there are some differences in it.

UDP is a connectionless protocol while TCP is connection oriented. UDP never track the data, so never shows the confirmation report, while TCP

track the data and show confirmation report, after receiving, if the data losses anywhere it resends that particular data.

18

Page 19: P2P Chat Server System

UDP transport the data in the form of Data packets, whereas TCP transport the data in long stream. It flows continuous. To make in the form of packets stack is required on the both end for reassembling them. In the sending end, stack breaks the flow of the data and sends the data in the form of packets, on the receiving end, the stack reassemble the data from packets to flowing form.

TCP has 20 bytes of overhead while UDP has only 8 bytes of overhead. Times can be established in TCP protocol in sending the data, because the data

packets goes one after one in the sequence form and each packets takes a specific time period, whereas no times period can be established in the UDP protocol case, because the data transmits in non-sequence form.

UDP transmit the data according to the generation of data, which is produced by the bandwidth of the Internet, if there is any obstacle in the network it could be lost due to the overflowing of data in the router. On the other hand TCP has a cognition control mechanism that indicates the senders about the congestion and it tolerate the transmitting process for some times.

IN spite of being so many demerits, UDP is very useful in some circumstances, especially in speed and network management. Its speed is faster than TCP protocol. UDP transports the data periodically and with no guarantee. So the updated data can be send after a certain period, which not only recovers the lost data but also it updates network. While in the TCP it is very difficult to recover the lost data at the congestion stage. It is also not suitable to carry network management due to its transmitting methodology.

UDP Server in JavaProviding you information relating to all technicalities of UDP server. This section provides you the brief description and program of the UDP server only for received your messages or information.

The UDP server UDP denotes a computing and technical terms that stands for User Datagram Protocol. Usually functioning as a connectionless datagram services with no guarantee of delivering data in a particular sequence. Any source host that requires a reliable communication has options of using either TCP or a program based on a sequential services. Generally all UDP messages are sent with the current IP address through ports.

19

Page 20: P2P Chat Server System

It helps in delivering messages from the source host to the ultimate destination as a postcard; small but not with a guarantee of delivery but TCP works like a telephone by verifying the destination address. Usually UDP is used to deliver a small amount of data to a large number of recipient at one set period of time. So it low over heading and multitasking capacity stands it ahead than TCP.

The Datagram The datagram is an unite of packet or packet for transfer in the TCP/IP network. Each datagram packet has data with source and destination address.

Description of program:

When you will run the program then a layout will appear on the screen that contains two buttons 'Start' and 'Stop' with a text area, where you receive your messages. The messages can be received only on that time when the UDP server is started. Whenever the UDP server is stopped then you can't be sent any message by the UDP client. If UDP server is started then it display the the message "Server is started" in the text area otherwise it shows "Server is stopped" or no any message in the text area.

Description of code:

Thread():Thread is a constructor of Thread class. The Thread class extends the Object and implements theRunnable. It creates a new thread object. Where you require, the executing of program continuously you can be used thread.

thread.start():This method starts the thread for executing the program. The run() method is called automatically when the start() method is execute.

thread.interrupted():The above method interrupts the thread that means breaking the thread for some time. If you want to start the thread again you can start it.

DatagramSocket(int port):DatagramSocket is the constructor of DatagramSocket class. This class extends Object.

20

Page 21: P2P Chat Server System

It creates the datagram socket and takes only integer  port number. This socket binds the specified port number where the messages is send on the local host machine.

append(String str):This method is used to insert or append given the string in it.

DatagramPacket(byte[] buffer, int buffer_length):This constructor provided by the DatagramPacket class. This class extends the Object and imports the java.net.*. It constructs a DatagramPacket to the receiving packet length. It takes the buffer size and buffer length. Where the connectionless services are provided by the user then use it. 

receive(DatagramPacket packet):The datagram packet received by this method from the specified socket.

InetAddress:This class extends the Object and implements the Serializable. It displays the IP address. 

getAddress():Above method returns the IP address of the object of InetAddress class, where the datagram packet can be send or receive.

getPort():This method returns the port number of the host machine. Where the datagram packets can be send or receive.

socket.close():This method closes the datagram socket that means you can not be received any messages.

  

Sending and receiving information to the UDP Client in JavaHere, you will provide send and receive information by the UDP client in Java. UDP client sends information or messages to UDP server and it collects some messages from UDP server.

21

Page 22: P2P Chat Server System

Description of program:

When you will run the program then appears a graphical layout on the screen. Which has destination IP (Internet protocol) address (localhost or 127.0.0.1), destination port number (8080), a text area and a 'Send' command button. All information or messages are written by client in a text area after that you clicked on the 'Send' button then messages to be send into the UDP server and it also sends a message to UDP client in the text area. Therefore UDP client can identify that your sending information are received or not by the UDP server.

Receiving and sending a request to UDP server in JavaHere, you will know how to receive and send messages by UDP server. First of all, UDP server receives messages and sends some information to UDP client. The brief descriptions are available bellow:

Description of program: 

This program provides you a layout. Which contains two command buttons 'Start' and 'Stop' with a text area. Messages are received by the UDP server in a text area at the time of server is started. If server is start then shows a message "Server is started" in the text area and if stopped then shows a message like: "Server is stopped" and no any information or messages are received by server. Any information are collected by UDP server then it sends a message to UDP client. 

Multicast in Java

This section introduces you how to deliver or transmit data in network and describes the fundamental of various techniques like: unicast, broadcast and multicast. The detail information is given bellow: 

 There are following types  of method for delivering or transmitting data in the network.

1. Unicast2. Multicast3. Broadcast

22

Page 23: P2P Chat Server System

1. Unicast: This method solves network traffic problems to deliver messages from one host to another. Here, data can be delivered to one specific destination IP (Internet Protocol) address that means only one sender sends data and another receives at a time. So, you can say that this is one-to-one data delivering method like: walky-talky and telephone or mobile phone. These equipments provide the facility of transferring data only one user at a time. If one user uses this then another is not accessed. 

The unicast method is not efficient for network traffic problem because it supports one-to-one transmission that consumes more time and provides slow processing for deliver data from one user to another.

2. Multicast: In this method, you can transmit data or messages to all destination host machines, which has been interested an appropriate multicast  group. The sender generates only one data stream but it delivered to all destination hosts. It supports one-to-many data delivering networks. Multicast delivers a data or information simultaneously to all interested destination hosts machines. The multicast methodology are used in case of teleconferencing and videoconferencing. The teleconferencing and videoconferencing machines transmit data simultaneously to all interested parties present in the same group.

Multicast provides the best features to unicast and broadcast because, here neither carries the burden of data to delivering all hosts nor miss-utilize the entire network. Users are joined in the multicast groups to follows an appropriate standards like: IP Multicast and Mbone.

In case of addressing and classifying the entire network, multicast is placed in a class 'D' IP address and which has addresses space 224.0.0.0 to 239.255.255.255.

3. Broadcast: It provides better facility to solve a network traffic problems than unicast. In broadcast, the server generates only one data stream but it can be delivered to all destination host whether interested or not. Here transmitting data or packets to be received by every host machine on entire network that means you send data or messages to multiple host at a time or simultaneously. It uses in the e-mail systems and some fax system. In case of e-mail and fax system, you give more than one addresses in place of address and send it then all destination receive this message simultaneously. 

This data delivering process is fast but a network carries more burden in delivering. So, the values of network resources are worst and miss-utilize the entire network. Ethernet

23

Page 24: P2P Chat Server System

and IPv4 are used to represent the broadcast address and packet but IPv6 does not support directed broadcasts or local broadcasts.

Multicast Server in JavaThis section introduces how to receive and send the IP packet by the multicast server and provides the functionality of multicast server through program. A brief description is given bellow. 

Description of program:

Here, a graphical layout appears on the screen when program runs that has two command buttons 'Start' and 'Stop'. First time 'Start' button is enable and another is disable. When you click 'Start' button, the multicast server functions but button is disable, and the message "Server is started" is displayed in text area. If you want to stop the server then click on the 'Stop' button then multicast server resume its function with a message that "Server is stopped". The multicast server receives requests or messages from multicast client, which has the port number '5000' and IP(Internate Protocol) number ('224.0.0.0', '235.0.0.1', '235.255.0.1', '224.0.255.1'). The server also sends same message to all multicast clients that are interested for this group otherwise don't perform these works. 

Description of code:

MulticastSocket(int port):This is the constructor of MulticastSocket class. This class imports from import java.net.* package and extends the DatagramSocket that can be used for sending or receiving the multicast IP packets. It is same as DatagramSocket (UDP) and provides an extra facility to joining 'groups' of multicast hosts on the Internet. The above constructor constructs multicast socket. It takes integer type port number to bound it.

DatagramPacket(byte[] buf, int length, InetAddress address, int port):DatagramPacket is a constructor of DatagramPacket class. This class extends the Object and imports form import java.net.* package that can be used for delivering the connectionless packet so packet delivering is not guarantee at the destination host. This constructor creates a datagram packet and delivers or transfers packet length to specified port number at the specified host. 

24

Page 25: P2P Chat Server System

 Multicast Client in JavaThis section describes the ways to send and receive the IP packet or message by multicast client. Here, we provide many multicast clients and it's functionality for sending or receiving messages at a time. The detail information provides bellow:

Description of program: 

Program runs then it provides a graphical layout that has four clients identified by the specific IP('224.0.0.0', '235.0.0.1', '235.255.0.1', '224.0.255.1') and port number(5000). Those of any client sends and receives IP packet that depends upon the check box. If check box is enable then send or receive IP packets otherwise it couldn't be send or receive. Just bellow provides a text area that can be used for writing the message and receiving the message to multicast server. It has also 'Send' command button for sending IP packet to multicast server. 

I/O Streams

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.

No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:

Reading information into a program.

25

Page 26: P2P Chat Server System

A program uses an output stream to write data to a destination, one item at time:

Writing information from a program.

The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.

ntroduction to CollectionsA collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers).If you've used the Java programming language — or just about any other programming language — you're already familiar with collections. Collection implementations in earlier (pre-1.2) versions of the Java platform included Vector, Hashtable, and array. However, those earlier versions did not contain a collections framework.

What Is a Collections Framework?A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

26

Page 27: P2P Chat Server System

Apart from the Java Collections Framework, the best-known examples of collections frameworks are the C++ Standard Template Library (STL) and Smalltalk's collection hierarchy. Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. We believe that the Java Collections Framework breaks with this tradition, as you will learn for yourself in this chapter.

Benefits of the Java Collections FrameworkThe Java Collections Framework provides the following benefits:

Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. By facilitating interoperability among unrelated APIs, the Java Collections Framework frees you from writing adapter objects or conversion code to connect APIs.

Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.

Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. If my network administration API furnishes a collection of node names and if your GUI toolkit expects a collection of column headings, our APIs will interoperate seamlessly, even though they were written independently.

Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.

Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.

Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

What is Swing? To create a Java program with a graphical user interface (GUI), you'll want to

learn about Swing. The Swing toolkit includes a rich set of components for building GUIs and adding

interactivity to Java applications. Swing includes all the components you would

27

Page 28: P2P Chat Server System

expect from a modern toolkit: table controls, list controls, tree controls, buttons, and labels.

Swing is far from a simple component toolkit, however. It includes rich undo support, a highly customizable text package, integrated internationalization and accessibility support. To truly leverage the cross-platform capabilities of the Java platform, Swing supports numerous look and feels, including the ability to create your own look and feel. The ability to create a custom look and feel is made easier with Synth, a look and feel specifically designed to be customized. Swing wouldn't be a component toolkit without the basic user interface primitives such as drag and drop, event handling, customizable painting, and window management.

Swing is part of the Java Foundation Classes (JFC). The JFC also include other features important to a GUI program, such as the ability to add rich graphics functionality and the ability to create a program that can work in different languages and by users with different input devices.

The following list shows some of the features that Swing and the Java Foundation Classes provide.

Swing GUI Componentso The Swing toolkit includes a rich array of components: from basic

components, such as buttons and check boxes, to rich and complex components, such as tables and text. Even deceptively simple components, such as text fields, offer sophisticated functionality, such as formatted text input or password field behavior. There are file browsers and dialogs to suit most needs, and if not, customization is possible. If none of Swing's provided components are exactly what you need, you can leverage the basic Swing component functionality to create your own.

Java 2D APITo make your application stand out; convey information visually; or add figures, images, or animation to your GUI, you'll want to use the Java 2D API. Because Swing is built on the 2D package, it's trivial to make use of 2D within Swing components. Adding images, drop shadows, compositing — it's easy with Java 2D.

Pluggable Look-and-Feel Supporto Any program that uses Swing components has a choice of look and feel.

The JFC classes shipped by Sun and Apple provide a look and feel that matches that of the platform. The Synth package allows you to create your own look and feel. The GTK+ look and feel makes hundreds of existing look and feels available to Swing programs.

o A program can specify the look and feel of the platform it is running on, or it can specify to always use the Java look and feel, and without recompiling, it will just work. Or, you can ignore the issue and let the UI manager sort it out.

Data TransferData transfer, via cut, copy, paste, and drag and drop, is essential to almost any application. Support for data transfer is built into Swing and works

28

Page 29: P2P Chat Server System

between Swing components within an application, between Java applications, and between Java and native applications.

Internationalizationo This feature allows developers to build applications that can interact with

users worldwide in their own languages and cultural conventions. Applications can be created that accept input in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.

o Swing's layout managers make it easy to honor a particular orientation required by the UI. For example, the UI will appear right to left in a locale where the text flows right to left. This support is automatic: You need only code the UI once and then it will work for left to right and right to left, as well as honor the appropriate size of components that change as you localize the text.

Accessibility APIPeople with disabilities use special software — assistive technologies — that mediates the user experience for them. Such software needs to obtain a wealth of information about the running application in order to represent it in alternate media: for a screen reader to read the screen with synthetic speech or render it via a Braille display, for a screen magnifier to track the caret and keyboard focus, for on-screen keyboards to present dynamic keyboards of the menu choices and toolbar items and dialog controls, and for voice control systems to know what the user can control with his or her voice. The accessibility API enables these assistive technologies to get the information they need, and to programmatically manipulate the elements that make up the graphical user interface.

Undo Framework APISwing's undo framework allows developers to provide support for undo and redo. Undo support is built in to Swing's text component. For other components, Swing supports an unlimited number of actions to undo and redo, and is easily adapted to an application. For example, you could easily enable undo to add and remove elements from a table.

Flexible Deployment SupportIf you want your program to run within a browser window, you can create it as an applet and run it using Java Plug-in, which supports a variety of browsers, such as Internet Explorer, Firefox, and Safari. If you want to create a program that can be launched from a browser, you can do this with Java Web Start. Of course, your application can also run outside of browser as a standard desktop application.

Part 5 Testing:

The goal of testing is to locate system errors before installation these system errors can

take different forms including the coding errors that reduce system efficiency. For this

29

Page 30: P2P Chat Server System

reason a systematic testing procedure has been adopted which covers all functions, even

the ones that are certain to work. The following are the testing approaches are used:

1. Black box testing

2. White box testing

3. User interface testing

4. Functionality testing

5. Load Testing

1. Black box testing

The test was based on checking the requirements stated on the system request in

the first milestone of the project. The fully developed product was crosschecked with

functionality stated in the system request document and it has been found that all the

promised features are present and functioning successfully.

2. White box testing

The programmer of the project added comments to the processes performed by the

system. This is done for future readability and a guide line for the code. The coding for

the interface follows the formal coding standard and has been reviewed by the

programmer. The system analyst and the programmer have conducted several sessions of

“code walk-through” to avoid errors. Programmer is proud to state that this part of

program testing was completed successfully.

3. User interface testing

The user interface testing includes the following subcategories identified by the team:

3.1 The three click rule testing

3.2 Loading time testing

3.3 Response time testing

3.4 Product Headings

3.5 Format Testing

30

Page 31: P2P Chat Server System

3.6 User experience testing

Test Condition Id: 3.1 Tester: H.M.

Requirements Addressed: User interface/usability.

Test Objective: Test conducted to check if the feasibility” three mouse click rule”.

Data Field:

NA

Value Entered:

NA

Expected Result: A test conducted to check if the user is able to navigate from main page to

any action within three mouse clicks for all the features offered.

Observed Result : The programmer was able to navigate from main page to any action

within three mouse clicks

Test Passed / Failed: The test was successful.

Test Condition Id: 3.2 Tester: H.M.

Requirements Addressed: User interface/usability

31

Page 32: P2P Chat Server System

Test Objective: Test conducted to record the time taken for each client-interface to load.

Data Field:

N/A

Value Entered:

Mouse clicks.

Expected Result: The Client-Interface takes a very minimum time of two seconds to load.

Observed Result: The observed result was same as the expected result.

Test Passed / Failed: The test was successful.

Test Condition Id: 3.3 Tester: H.M.

Requirements Addressed: User interface/usability

Test Objective: Test conducted to record the response time of the system.

32

Page 33: P2P Chat Server System

Data Field:

Send.

Value Entered:

Mouse clicks.

Expected Result: The results are expected to appear within two seconds of clicking the

mouse. This applies to a very large message.

Observed Result: The observed result was same as the expected result.

Test Passed / Failed: The test was successful.

Test Condition Id: 3.4 Tester: H.M.

Requirements Addressed: User interface/usability

Test Objective: Test conducted to crosscheck the headings in Client Interface for user-

friendly names.

33

Page 34: P2P Chat Server System

Data Field:

Machine:port

User Name

Join Chat

Private message To.

Type Message Here

Send.

Value Entered:

Machine name:port number of the server

Mouse clicks.

User name.

Mouse clicks

User Name to Send private message

Message

Mouse clicks.

Expected Result: The column names for each input are expected to be meaning-full defining

the functionality. This enable the users to understand the various the functionality of various

fields.

Observed Result: The observed result was same as the expected result.

Test Passed / Failed: The test was successful.

Test Condition Id: 3.5 Tester: H.M.

Requirements Addressed: User interface/usability

Test Objective: Test conducted to explain the format of entry in each data field for the users

34

Page 35: P2P Chat Server System

Data Field:

Machine:port

User Name

Join Chat

Private message To.

Type Message Here

Send.

Value Entered:

Machine name:port number of the server

Mouse clicks.

User name.

Mouse clicks

User Name to Send private message

Message

Mouse clicks.

Expected Result: The interface is expected to balance the requirement of both the novice

and experienced users by displaying the format for entry of data in all the products.

Observed Result: The interface developed by the team displayed the format for entry of data

in each field.

Test Passed / Failed: The test was successful.

Test Condition Id: 3.6 Tester: H.M.

Requirements Addressed: User interface/usability

Test Objective: Test conducted to crosscheck between user experience and the interface

developed.

35

Page 36: P2P Chat Server System

Data Field:

Machine:port

User Name

Join Chat

Private message To.

Type Message Here

Send.

Value Entered:

Machine name:port number of the server

Mouse clicks.

User name.

Mouse clicks

User Name to Send private message

Message

Mouse clicks.

Expected Result: The interface is expected to balance the requirement of both the novice

and experienced users.

Observed Result: The observed result was same as the expected result.

Test Passed / Failed: The test was a success.

4. Functionality Testing:Test for - all the features of the chat-system interface used for submitting or getting text information from users involved in chat.

Check all the features:System has been tested for functionalities such as

1. Client connection with the server2. Private message to specific user logged on chat system.3. Public message to al users logged on to the chat system

36

Page 37: P2P Chat Server System

After testing all above stated features were found working properly.

Test User Interface:

The Client Interface is the integral part of Chat System. It is used to get information from users and to keep interaction with them. So following tests has been performed:

1. First check all the validations on each field.2. Check for the default values of fields.3. Wrong inputs to the fields in the forms.

System has been tested for validation as to start chatting client must supply valid name & port of the Chat server to connect and start communication. Client is also required to supply valid user name to start private chat.

5. Load testing

General Description:

This test ensures that the chat server can handle the maximum number of chat clients that the application advertises (i.e. 15 successful connections).

Data Files: None.

 Sequenc

eCondition Data

CharacteristicsExpected Results Actual Results

         1 Start a ChatClient

while the ChatServer is listening for a connection and use a valid username.

Client 1 Name = "person1"

The chat box for person1 reads: "Connection successful."

Results as expected.

2 Start 14 more ChatClient sessions with valid usernames.

Client2 name = "person2"

Client3 name = "person3"

Client4 name =

The chat box for person2 through person15 each reads: "Connection successful."

Results as expected.

37

Page 38: P2P Chat Server System

"person4"

Client5 name = "person5"

Client6 name = "person6"

Client7 name = "person7"

Client8 name = "person8"

Client9 name = "person9"

Client10 name = "person10"

Client11 name = "person11"

Client12 name = "person12"

Client13 name = "person13"

Client14 name = "person14"

Client15 name = "person15"

3 Start a ChatClient that is more than the allowable limit.

Client16 name = "person16"

The chat window is displayed and reads: "Trying to connect……."

Results as expected.

 

Part 6: Screenshots

38

Page 39: P2P Chat Server System

Chat Server started

39

Page 40: P2P Chat Server System

Client Interface Started through Command Prompt

40

Page 41: P2P Chat Server System

Client Interface

41

Page 42: P2P Chat Server System

Connection Established

42

Page 43: P2P Chat Server System

Connection Established

43

Page 44: P2P Chat Server System

Message Passing shown

44

Page 45: P2P Chat Server System

Public Message Passing Shown

45

Page 46: P2P Chat Server System

Part 7: Future Perspective

The following functions could be improved in the current information system as future

enhancements:

1. User Interface

User interface needs to be more interactive and provides the user with ease of

functionality. In current system User can quit chat any time, user should be asked for

confirmation prior to leaving system.

2. Security

User can join the chat system by simply providing the User Name. User should be

allowed to join the chat system only after supplying valid user credentials.

Following features can be added in the current system:

File-transfer support

community chat

animations, backgrounds, and funny smilies

skin change and customization

multi-language interface

audio-visual chat

allow the user to customize sound/video quality

Users Management

administering module

multi-server support

chat history

mark the user who refused private chat

optimized interface, drawing board, and message windows are set tab

customized chat window size

46

Page 47: P2P Chat Server System

Part 8 Conclusion:

This project Chat Server helps users to communicate with each otherthrough client server technology.It is an effective way to connect multiple clients and enable communication between the.It supports all sorts of language and text formats.

Part 9 Biblography:

Web sites:

http://java.sun.com

http://www.sourceforge.net/projects/jasperreports

http://ireport.sourceforge.net/index.html

http://javasoft.com/

http://javaworld.com/

Books:

a) Java 7 The Complete Reference by Herbert Schildtb) Head First Java –O’Reillyc) Black Book –Dr. R. Nageswara Rao

47

Page 48: P2P Chat Server System

48

Page 49: P2P Chat Server System

49

Page 50: P2P Chat Server System

50