0% found this document useful (0 votes)
60 views53 pages

Programming Module (A Secure Client-Server Chat Application) .

NOTE

Uploaded by

abass muyiwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views53 pages

Programming Module (A Secure Client-Server Chat Application) .

NOTE

Uploaded by

abass muyiwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

DESIGN AND IMPLEMENTATION OF A NETWORK

PROGRAMMING MODULE (A SECURE CLIENT-SERVER


CHAT APPLICATION).

CHINEDU INNOCENT UKAEGBU (NOU156210063)


DEPARTMENT OF COMPUTER SCIENCE,
NATIONAL OPEN UNIVERSITY OF NIGERIA
[email protected]

ABSTRACT
Several network systems are built to communicate with one another as well as made available

through service-oriented architectures. In this project, the client server architecture is used to

develop a chat application. Firstly a chat application is created for both Client and Server

which is based on Transmission Control Protocol (TCP) where TCP is connection oriented

protocol and is a reliable connection protocol. As security is the key factor while communicating

over a network, so in this project, MySQL SSL protocol and hash function was used for the

Database based on a numbers of benefits. The hash values of the real password and the random

generated number (salt) is stored in the database. The original password is not stored on the

system, makingcracking of password much harder.

Keywords: Client Server, Model, Network, Port, TCP, Encryption.

i
1.0 INTRODUCTION

Several network systems are built to communicate with one another and are made available

through service-oriented architectures. In this project, we use the client server architecture to

develop a secured Client-Server chat application. A chat application is created based on

Transmission Control Protocol (TCP) where TCP is connection oriented protocol and in the end,

multithreading is used to develop the application.

A client-server chat application consists of a Chat Client and a Chat Server and there exists a two

way communication between them. Here, Message Processor is used to interpret message from

the user, Message Interpreter is used to extract and pass the received message. Message Maker is

used to construct back the message and Client Manager is used to maintain the clients list which

the sender and receiver at both sides use to interact with each other.

In general, the server process will start on some computer system; in fact, the server should be

executed before the client. Server usually initializes itself, and then goes to wait state or sleep

state where it will wait for a client request. After that, a client process can start on either the

same machine or on some other machine. Whenever the client wants some service from the

server, it will send a request to the server and the server will accept the request and process it.

After the server has finished providing its service to the client, the server will again go back to

sleep, that is, waiting for the next client request to arrive. This process is repeated as long as the

server processes is running. Whenever such request comes, the server can immediately serve the

client and again go back to the waiting state for the next request to arrive.

1
1.1 BACKGROUND OF THE STUDY

Client server model is the standard model which has been accepted by many for developing

network applications. In this model, there is a notion of client and notion of server. As the name

implies, a server is a process (or a computer in which the process is running) that is offering

some services to other entities which are called clients. A client on the other hand is process

(which is running) on the same computer or other computer that is requesting the services

provided by the server.

A chat application is basically a combination of two applications:

 Server application

 Client application

Server application runs on the server computer and client application runs on the client computer

(or the machine with server). In this chat application, a client can send data to anyone who is

connected to the server.

Java application programming interface (API) provides the classes for creating sockets to

facilitate program communications over the network. Sockets are the endpoints of logical

connections between two hosts and can be used to send and receive data. Java treats socket

communications much as it treat input and output operations; thus programs can read from or

write to sockets as easily as they can read from or write to files.

To establish a server connection, a server socket needs to be created and attached to a port,

which is where the server listens for connections. The port recognizes the Transmission Control

2
Protocol service on the socket. For instance, the email server runs on port 25, and the web server

usually runs on port 80.

Server Execution: At server the side, a thread is created which receives numerous clients’

requests. It also contains a list in which Client’s name and IP addresses are stored. After that, it

broadcast the list to all the users who are currently in chat

room and when a client logs out then server deletes that particular client from the list, update the

list and then broadcast the list to all available clients.

Client Execution: A client firstly must have to register itself by sending username to the server

and should have to start the thread so that system can get the list of all available clients. Then any

of two registered clients can communicate with each other.

1.2 STATEMENT OF THE PROBLEM

The client-server communication model is used in a wide variety of software applications. Where

normally the server side is sufficiently protected and sealed from public access, but client

applications running on devices like notebooks and desktops are considered insecure and

exposed to security threats.

The main weakness of client-server chat application is that there is no security provided to data

which is transferred between clients. Any unauthorized client can hack the client account and can

change the data. This is the main objective of this project (To develop a secured Client-Server

Chat Application).

3
1.3 OBJECTIVES OF THE STUDY

The aim of this project is to develop a reliable and secure network programming (Client-Server

chat model) which can perform a multithreaded server client chat application based on Java

socket programming using Transport Control Protocol (TCP). As security is the key factor while

communicating over a network, hash function with salt is used for the Database based on a

number of benefits. MySQL became the choice for the implementation of this application based

on its scalability and flexibility, high performance, high availability, strong data protection, web

and data warehouse strengths, management ease, lowest total cost of ownership and open source

freedom.

1.4 SIGNIFICANCE OF THE STUDY

Apart from just performing the regular client server chat, this client-server chat is robust and

significant in the following ways:

This project use MySQL for its database to make information in the database secure. The

personal details and messages including the private messages in the Database are encrypted

using encryptor (one of the security facilities available in the MySQL).

This project implements hash function with the password before the encryption and then stored

in the Database. It also uses random generated numbers (salt) that is calculated together with the

passworded hash values and stored in the Database. As a result, even if the database is

compromised, the salt added to hash values makes it harder to compute the original password.

This random salt is used with the hash function to significantly increase the strength of

4
encrypting passwords and thus makes cracking greatly impossible. This makes the chat

application server reliable and more secured.

Another significance of this application is private chatting. This is where two users can chat in

private. The messages between the users are not displayed/seen in the general chat display text

field. The messages are displayed only within the private message display text field.

1.5 SCOPE OF THE STUDY

The project shall consider among other things the following issues:

1. To provide a better understanding of how network programming in java works.

2. Develop a reliable network communication for a Client-Server chat application.

3. Analyses of network programming in java (Multithreaded Client-Server Chat

applications) for better understanding of the solutions.

4. Conduct an experimental result in order to establish the parameter of the problem. In

conclusion, suggest ways the problems can be eliminated and recommends how the

problems can be prevented.

1.6 LIMITATIONS OF THE STUDY

The previous Client-Server Chat system implements only hash function with the password before

the encryption which is then stored in the Database. Thus, the database can be compromised

easily to compute the original password.

Some drawbacks of the Client-Server Chat are as follows:

5
1. As the server receives as many requests from clients so there is a chance that server can

become congested and overloaded.

2. In case of server fails then the users also suffers.

3. A lost password is irrecoverable.

4. Any unauthorized client can hack the client account and can change the data.

1.7 ORGANISATION OF WORK

In this project, a secure java chat application is considered which relies on the client-server

paradigm to exchange the information. It is divided into five chapters. Chapter one is the

introduction which consists of the background of study, significance of the study, scope of the

study, limitations of the study, organization of the work and the definition of terms.

The second chapter focuses on the literature review of relevant scholar’s opinions relevant to this

study such as socket programming in java, overview of secure socket layer, hash function e.t.c.

The third chapter gives details of the main methodology and system design to implement the

client-server chat application in java. First of all the application is developed by using TCP then

and in the end multithreading is used to develop the application. At the end of chapter

weaknesses (deadlocks) of multithreading is discussed which can be removed by using

synchronizing threads.

The fourth chapter describes the implementation of the secured Java Client-Server Chat

Application: it test and analysis the implementation of the application.

6
The fifth chapter ends the project report. Firstly, a short summary highlights the main points of

the whole project. Next, a number of conclusions and recommendations are given and lastly

Appendix.

1.8 DEFINITION OF TERMS

Socket: Socket is a standard connection protocol that supports data communication over the

network between connected terminals. The standard connection supports the data transmission

both by the TCP and UDP protocols between the terminals.

TCP: TCP is a transport layer protocol used by applications that require guaranteed delivery of

data. Basically, it is a connection-oriented protocol. To communicate over TCP one must first

have to establish a connection between pair of sockets, where one socket is client and the other

belongs to server. After the connection is established between them then they can communicate

with each other.

Client: A client is a system that accesses or desires for a service made accessible by a server.

Server: A server is a system (hardware or software) program running to provide the service

requests of other system programs.

Port: Port is a software mechanism that allows the centralized connected Servers to listen for

requests made by clients. Port is actually purposed as a gateway to listen for the requested

parameters by the server terminals or other machines. It is a software address on a system that is

on the network. Entire request response proceeding among this Application is carries through

machine ports.

7
Network: This refers to a system were computers are linked to share software, data, hardware

and resources for the benefit of users.

Interface: This may be software or hardware that upon an agreed method spells out the manner a

system component can exchange information with another system component.

Secure socket layer (SSL): This refers to Secure Sockets Layer protocol that is used for

encryption of data for secure data transmission. IP: This refers to Internet Protocol; it is the

reasonable network address of device on a network. It is notational called dotted-decimal (for

instance: 128.1.0.1).

Thread: A thread is a section of code which is executing independently of others threads in a

same program. Java has a class Thread which is defined in java.lang package. Thread is the most

powerful feature that JAVA supports from other programming languages.

8
2.0 LITERATURE REVIEW

In Communications technology, client-server is a software architecture model consisting of two

parts, client systems and server systems both communicating over a computer network or on the

same computer. A client-server application is a distributed system consisting of both client and

server software. The client process always initiates a connection to the server, while the server

process always waits for requests from any client. When both the client process and server

process are running on the same computer, this is called a single seat setup.

The client-server relationship describes the relation between the clients and how it makes a

service request from the server and how the server can accept these requests, process them and

return the requested information to the client.

2.1 CLIENT-SERVER AND OTHER MODELS

The client-server model according to Hou Meng-bo (May 2008) was originally developed to

allow more users to share access to database applications. Compared to the mainframe approach,

client-server offers improved scalability because connections can be made as needed rather than

being fixed.

Client-server is just one approach to managing network applications. The primary alternative,

peer-to-peer networking, models all devices as having equivalent capability rather than

specialized client or server roles. Compared to client-server, a peer to peer network offers some

advantages such as more flexibility in growing the system to handle large number of clients.

Client-server networks generally offer advantages in keeping data secure.

9
2.2 CLIENT-SERVER COMMUNICATION

According to Fisher Price Et al (2011) at a basic level, network-based systems consist of a

server, client and a media for communication as shown in the figure below. A computer running

a program that makes a request for services is called client machine. A computer running a

program that offers requested services from one or more clients is called server machine. The

media for communication can be wired or wireless network.

Figure 2.1 media for communication process (wired or wireless network).

Generally, programs running on client machines make requests to a program (often called as

server program) running on a server machine. They involve networking services provided by the

transport layer which is part of the Internet software stack often called TCP/IP (Transport

Control Protocol/Internet Protocol) stack. The transport layer comprises two types of protocols,

TCP (Transport Control Protocol) and UDP (User Datagram Protocol). The most widely used

programming interfaces for these protocols are sockets.

TCP is a connection-oriented protocol that provides a reliable flow of data between two

computers. Example applications that use such services are HTTP, FTP, and Telnet.

10
UDP is a protocol that sends independent packets of data, called datagram, from one computer to

another with no guarantees about arrival and sequencing. Example applications that use such

services include Clock server and Ping.

2.3 HOSTS IDENTIFICATION AND SERVICE PORTS

Every computer on the Internet is identified by a unique, 4-byte IP address. This is typically

written in dotted quad format like 128.250.25.158 where each byte is an unsigned value between

0 and 255. This representation is clearly not user-friendly because it does not tell us anything

about the content and then it is difficult to remember. Hence, IP addresses are mapped to names

like www.nouonline.net or www.google.com, which are easier to remember. Internet supports

name servers that translate these names to IP addresses. In general, each computer only has one

Internet address. However, computers often need to communicate and provide more than one

type of service or to talk to multiple hosts/computers at a time. For example, there may be

multiple ftp sessions, web connections, and chat programs all running at the same time. To

distinguish these services, a concept of port, a logical access point is used. This means that each

service offered by a computer is uniquely identified by a port number. Each Internet packet

contains both the destination host address and the port number on that host to which the

message/request has to be delivered. The host computer dispatches the packets it receives to

programs by looking at the port numbers specified within the packets. That is, IP address can be

thought of as a house address when a letter is sent via post/snail mail and port number as the

name of a specific individual to whom the letter has to be delivered.

11
2.4 SOCKETS AND SOCKET-BASED COMMUNICATION

Sockets provide an interface for programming networks at the transport layer. Network

communication using sockets is very much similar to performing file I/O. Socket handle is

treated like file handle according to Ming Xue Et al. The streams used in file I/O operation are

also applicable to socket-based I/O. Socket-based communication is independent of a

programming language used for implementing it. This means that a socket program written in

Java language can communicate to a program written in non-Java (say C or C++) socket

program. A server (program) runs on a specific computer and has a socket that is bound to a

specific port. The server listens to the socket for a client to make a connection request. 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 (consequently a different port number) so

that it can continue to listen to the original socket for connection requests while serving the

connected client.

2.5 TCP/IP SOCKET PROGRAMMING

The two key classes from the java.net package used in creation of server and client programs are:

 ServerSocket

 Socket

A server program creates a specific type of socket that is used to listen for client requests (server

socket). In the case of a connection request, the program creates a new socket through which it

will exchange data with the client using input and output streams. The socket abstraction is very

similar to the file concept: developers have to open a socket, perform I/O, and close it.

12
2.6 SOCKET PROGRAMMING IN JAVA

According to Gandhi P. Et al (2010) a socket is the one end-point of a two-way communication

link between two programs running over the network. Running over the network means that the

programs run on different computer. However one can run these two programs on the same

computer. These two communicating programs form a Client-Server application.

In Client-Server applications, the server normally listens to a specific port waiting for connection

requests from a client. When a connection request arrives, the client and the server establish a

dedicated connection to communicate. During the connection process, the client is assigned a

local port number, and binds a socket to it. The client talks to the server by writing to the socket

and gets information from the server by reading from it. Similarly, the server gets a new local

port number to communicate with the client. The server also binds a socket to its local port and

communicates with the client by reading from and writing to it. The server uses a specific port

dedicated only to listening for connection requests from other clients. The client and the server

must agree on a protocol. They must agree on the language of the information transferred back

and forth through the socket.

The java.net package in the Java development environment provides the class Socket which

implements the client side and the class ServerSocket class which implements the server side of

the two-way link.

2.7 SECURE INTERNET PROGRAMMING

According to H. Mahmoud (November 2008) any information transmitted over computer

networks or the Internet is subject to interception. Some of that information could be sensitive

13
such as credit card numbers and other personal data. To make the Internet more useful in an

enterprise setting and for e-commerce, applications must protect their users' information using

encryption, authentication, and secure communications protocols. The secure Hypertext Transfer

Protocol (HTTPS), which is HTTP over the Secure Sockets Layer (SSL), is already being used

successfully for e-commerce applications.

2.8 OVERVIEW OF SECURE SOCKET LATER (SSL)

The SSL protocol which was developed by Netscape in 2010, allows clients (Web browsers,

typically) and HTTP servers to communicate over a secure connection. It offers encryption,

source authentication and data integrity as means to protect information exchanged over

insecure, public networks.

Encryption: It protects data from unauthorized users by converting it to an apparently

meaningless form before transmission. The data is encrypted by one side (the client or the

server), transmitted, decrypted by the other side, and then processed.

Source authentication: It is a method of verifying the data sender's identity. The first time a

browser or other client attempts to communicate with a Web server over a secure connection, the

server presents the client with a set of credentials in the form of a certificate.

Data integrity refers to means of ensuring that data has not been modified in transit.

2.9 SECURITY

According to Gutman, Naccache, Palmer C. (2005, June), there are many aspects to security and

many applications ranging from secure commerce and payments to private communications and

protecting passwords.

14
2.9.1 CRYPTOGRAPHY

Cryptography is the science of writing in secret code and is an ancient art; the first documented

use of cryptography in writing dates back to circa 1900 B.C. when an Egyptian scribe used non-

standard hieroglyphs in an inscription. Within the context of any application-to-application

communication, there are some specific security requirements, including:

 Authentication: The process of proving one's identity. (The primary forms of host-to-

host authentication on the Internet today are name-based or address-based.)

 Privacy/confidentiality: Ensuring that no one can read the message except the intended

receiver.

 Integrity: Assuring the receiver that the received message has not been altered in any

way from the original.

 Non-repudiation: A mechanism to prove that the sender really sent this message.

Cryptography not only protects data from theft or alteration but can also be used for user

authentication.

In all cases, the initial unencrypted data is referred to as plaintext. It is encrypted into ciphertext

which will in turn (usually) be decrypted into usable plaintext.

2.9.2 TYPES OF CRYPTOGRAPHIC ALGORITHMS

There are several ways of classifying cryptographic algorithms which are as follows:

 Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption.

15
 Public Key Cryptography (PKC): Uses one key for encryption and another for

decryption.

 Hash Functions: Uses a mathematical transformation to irreversibly "encrypt"

information.

2.9.3 HASH FUNCTIONS

Hash functions, also called message digests and one-way encryption are algorithms that in

some sense use no key. Instead, a fixed-length hash value is computed based upon the

plaintext that makes it impossible for either the contents or length of the plaintext to be

recovered. Hash algorithms are typically used to provide a digital fingerprint of a file's

contents often used to ensure that the file has not been altered by an intruder or virus. Hash

functions are also commonly employed by many operating systems to encrypt passwords.

Hash functions then provide a measure of the integrity of a file.

2.9.4 TYPES OF HASH ALGORITHMS

 Message Digest (MD) algorithms: A series of byte-oriented algorithms that produce a

128-bit hash value from an arbitrary-length message.

 Secure Hash Algorithm (SHA): Algorithm for NIST's Secure Hash Standard (SHS).

SHA-1 produces a 160-bit hash value and was originally published as FIPS 180-1 and

RFC 3174. FIPS 180-2 (aka SHA-2) describes five algorithms in the SHS: SHA-1 plus

SHA-224, SHA-256, SHA-384, and SHA-512 which can produce hash values that are

224, 256, 384, or 512 bits in length, respectively.

16
 Hash of Variable Length (HAVAL): Designed by Y. Zheng, J. Pieprzyk and J. Seberry,

a hash algorithm with many levels of security. HAVAL can create hash values that are

128, 160, 192, 224, or 256 bits in length.

 Whirlpool: Whirlpool operates on messages less than 2256 bits in length, and produces a

message digest of 512 bits. The design of this has function is very different than that of

MD5 and SHA-1, making it immune to the same attacks as on those hashes.

17
3.0 SYSTEM ANALYSISAND DESIGN

3.1 METHODOLOGY

The Structured Systems Analysis and Design Methodology (SSADM) is a well- defined

(structured) methodology. It is an integrated set of standards and guides for the analysis and

design of computer systems. It is an integrated set of standards and guidelines consisting of:

 Structural standards: This defines the structure of a development project in the form of
explicitly defined tasks, with clearly defined interfaces between them, and clearly defined

tangible products.

 Technique guides: This provides development staff with a set of proven usable techniques
and tools, and detailed rules and guidelines on when and how to use them; and

 Documentation standards: This provides the means of recording the products of


development activity at a detailed level.

SSADM is waterfall method by which an Information System design can be arrived at (the

waterfall model is depicted in figure 3.1); SSADM can be thought to represent a pinnacle of

the rigorous document-led approach to system design. Benefits of the Structured Systems

Analysis and Design Methodology (SSADM) are:

1. Delivers the system to users on time: SSADM has a modular structure which relates

directly to project deliverables and helps in all aspects of project management. It gives a

18
clear specification of what is to be produced and how it is to be managed and reviewed.

There are well defined interfaces to management and specialist techniques.

2. Delivers systems that meets user's needs: By continuously involving users, by

modeling business activities and work practice, by using prototyping, by making the IT

professional's thinking visible through diagrammatic techniques, SSADM enhances the

prospects for success on large and small projects.

3. Improves quality by reducing error rates: Quality can be improved by detecting errors

early in the lifecycle, especially by involving users as well as skilled practitioners in

checking for errors. Rigorous techniques promote accuracy, with adequate checks of

completeness and consistency. By defining the required quality of design documents, and

stating the tests for them, SSADM promotes better quality management.

4. Improve flexibility: Every application development is different. The ability of tailoring

SSADM to suit different projects is a major factor for organizations who wish to reuse

their resource skills on other projects, and to be able to benefit from the many different

ways in which SSADM techniques and products may be applied.

5. Avoids IT developers’ bureaucracy: SSADM has been designed to provide useful tools

for project managers and to transfer expertise to practitioners. Its use makes benefits, as

well as costs, visible to both business and IT management and users.

19
Figure 3.1: The waterfall model

3.2 STAGES INVOLVED IN STRUCTURED SYSTEMS ANALYSIS AND DESIGN

METHODOLOGY

The SSADM method involves the application of a sequence of analysis, documentation and

design tasks concerned with:

1. Feasibility Stage

Analyze the current situation at a high level. A Data Flow Diagram is used to describe how the

current system works and to visualize known problems. The following steps are part of this

stage:

 Investigate and define requirements.

20
 Investigate current processing.

 Investigate current data.

2. Analysis Stage

The first part is researching the existing environment, where system requirements are identified

and the current business environment is modeled. Modeling consists of creating a Logical Data

Structure for processes and data structures that are part of the system. The following steps are

part of this stage:

 Requirements Specification Stage

 Define required system processing.

 Develop required data model.

 Derive system functions.

 Develop specification prototypes.

 Develop processing specification.

3. Logical System Specification Stage

In this stage, technically feasible options are chosen. The development/implementation

environments are specified based on this choice. The following steps are part of this stage:

 Logical System Specification Stage

 Define user dialogue.

 Define update processes.

 Define enquiry processes.

4. Physical Design Stage

21
The objective of this stage is to specify the physical data and process design, using the language

and features of the chosen physical environment and incorporating installation standards. The

following activities are part of this stage:

 Prepare for physical design.

 Complete the specification of functions.

 Incrementally and repeatedly develop the data and process designs.

3.3 DATA COLLECTION METHODOLOGY

3.3.1 PRIMARY DATA COLLECTION

The process of information gathering was achieved through so many sources including:

 Oral interview of users of existing system

 Textbooks in the library

 Newspaper, Journals and articles

 Other publications

3.3.2 SECONDARY DATA COLLECTION

 File downloads from the Internet

 Electronic media

3.4 ANALYSIS OF THE EXISTING SYSTEM

The existing Client-Server Chat system use TCP Transmission Control Protocol (TCP) that is

connection oriented. It is reliable; it guaranteed that each packet will arrive and also guaranteed

22
that packets will be in the right order. All personal details and messages including the private

messages in the Database are encrypted. It implements only hash function with the password

before the encryption and then stored in the Database. Thus, the database can be compromised

easily to compute the original password.

3.5 LIMITATIONS OF THE EXISTING SYSTEM

Since the existing system implements only hash function with the password before the

encryption and stored in the database, the password in the database can be hacked easily because

hash function can be decrypted easily using hash calculator.

The main weakness of the existing client-server chat application is that there is no security

provided to data which is transferred between clients. Any unauthorized client can hack the

client account and can change the data.

3.6 SYSTEM DESIGN

This Client-Server Chat system use Transmission Control Protocol (TCP) that is connection

oriented. It is reliable; it guaranteed that each packet will arrive and also guaranteed that packets

will be in the right order. All personal details and messages including the private messages in the

Database are encrypted. This project implements hash function with the password before the

encryption and then stored in the Database; also, this use random generated numbers (salt) that is

calculated together with the passworded hash value and stored in the Database. Thus, even if the

database is compromised, random generated salt added to hash value makes it harder to

compute the original password. Therefore, makes the server more secured. This chat system

implements real network connection. To implement the application on a real network, MySQL

23
must be installed on the server host. The client system must have all the classes compiled

without error. Thereafter, the user can start and use the same server IP address and Port number

to be able to establish connection with the server.

JAVA.NET Class: Java can be used easily to develop network applications. It comes with a

very powerful class library for networking as part of java.net package. The java.net package will

have to be included at the beginning of the program for network input and output methods

operations. By using TCP, the server runs first and then waits for client’s requests and sever has

ability to either accept or deny the client request. A server has a socket which is bound to a

specific port. Client programs send connection request to the server program and if everything is

well then server accepts the connection. After accepting the client request the server gets a new

socket bound to a different port, it requires a new socket bound because the original socket has to

listen to other connection requests.

Server Client
Connection Request
Port

Figure 3.2: Client Sending Connection Request to Server

Server Client

Port
Port
Connection
Port established

Figure 3.3: Client-Server Connection Established by using TCP

24
Socket Programming with TCP

TCP (Transfer Control Protocol) is a stream communication protocol basically it’s a connection-

oriented protocol. To communicate over TCP one must firstly have to establish a connection

between pair of sockets, where one socket is client and the other belongs to server. After the

connection is established between them then they can communicate with each other.

Client Program in JAVA:

1. To communicate with server program, the client has to create socket by writing the following

statement:

Socket client = new Socket(server, port_id);

Where server is the machine name you are trying to open a connection to and port_id is the port

number on which server and client are trying to connect. Port numbers have range from 0 to

65536, but port numbers range from 0 to 1023 are reserved for system use so select only the port

number greater than 1023 which are also available. The code written above cannot handle the

exceptions so the above code can be written as following, to handle the exceptions:

Socket client; try {

client = new Socket(server,port_id );

catch (IOException e) {

System.out.println(e);

25
2. The next step of the client program is to create an input, output stream to communicate with

the server. For this purpose use java DataInputStream for input and DataOutputStream or

PrintStream for output. Following is the code used to create an input stream to receive data from

server:

input = new DataInputStream(client.getInputStream());

String line = input.readLine();

And following is the code used to create an output stream to send data to the server socket:

output = new DataOutputStream(client.getOutputStream());

output.writeBytes(“Hello\n”);

The last step is to close socket but before closing the socket input and output stream must be

closed. Following the code for closing the socket:

try {

output.close();

input.close();

client.close();

catch (IOException e) {

System.out.println(e);

A Simple TCP Server Program in JAVA:

26
1. To communicate with client program first server has to create socket by writing the following

statement:

ServerSocket server = new ServerSocket(PortNumber);

Here again there is need to mention the PortNumber on which server and client are trying to

connect. The code written above cannot handle the exceptions so the above code can be written

as following, to handle the exceptions:

ServerSocket server; try {

server = new ServerSocket(PortNumber);

catch (IOException e) {

System.out.println(e);

2. In the server program, server also has to wait for client connection request and after getting

client request, the server has either to accept or deny the request. The following is the code

below to listen and accept the client request:

Socket clientSocket = null; try {

serverSocket = server.accept();

catch (IOException e) {

System.out.println(e);

27
3. In the server program, use java DataInputStream to receive input from client and use

DataOutputStream to send information to client. Following is the code used to create an input

stream to receive data from client:

input = new DataInputStream(server.getInputStream());

String line = input.readLine();

And following is the code used to create an output stream to send data to the client socket:

output = new DataOutputStream(server.getOutputStream());

output.writeBytes(“Hello\n”);

4. The last step is to close socket but before closing the socket input and output stream must be

closed. Following the code for closing the socket:

try {

output.close(); input.close();

serverSocket.close();

server.close();

catch (IOException e) {

System.out.println(e);

Client-Server Chat Application using TCP in JAVA:

A chat application is basically a combination of two applications:

28
 server application

 client application

Server application runs on the server computer and client application runs on the client

computer. In chat application, a client can send data to anyone who is connected. Either data can

be directly sent to anyone who is connected or it can be sent by informing server. This

application uses the second method, because in this case client is connected to only server and

can communicate with many clients and server doesn’t transmit the IP of client to anyone which

increases the security of the client.

Send message
Forward message
to the server
to the addressee

Figure 3.4: Client-Server Chat Application by using TCP

Before start chatting, the client must have to establish a connection with the server. In this

application, we have one server and many clients who can communicate to each other via server.

Client must encode the data in the language which is understandable by both the server and the

other client. The chat application will work in the following sequence:

 A client can chat only if it’s authenticated, so firstly a client must authenticate from by

sending its “id”. The “id” of each client must be unique.

29
 The server maintains a list of authenticated clients and sends the list to all authenticated

clients.

 The Server can send any message to any client, and the server also has the authority to

disconnect any client from chat system.

 A client can send messages or chat with any authenticated clients.

Server Execution:

Firstly all the clients have to connect with server, for this purpose server should have to listen for

client connection requests. So at server side, firstly a thread is created which accepts the client

connection request.

Implementation of a simple server program in java which can implement the client illustrates

when a client program connects to this server, it sends a welcome message back to the client,

then it will expect the client to send some data and whatever data it received from client, it will

simply echo it back, one line at a time.

Multicasting: In case clients wants to do a group chat then it sends request to the server and in

answer, server provides a group IP to the client and send information about the room to all the

concerned clients. Now when clients sends a message then it will multicast to all the clients in

group IP. In case of system failure, it may be server sender or receiver that failed then there will

be three stages which can be show using following figure 3.5:

30
Stage 2

Stage 1 Stage 3

t0 t1 t2 t3

Figure 3.5 Three Stages of System failure

 In case system of sender get failed at stage 1 then packet will save in the queue and will not

send until sender recovers but in case when receiver fails then packet will not be received.

 In case of sender fails at stage 2, the packet is already sent from the sender buffer and now

it is on the way. In this condition, the receiver will receive the message but if at this stage it

fails then, the message will not be received.

 In case sender get fails at stage 3, the packet is in receivers buffer so it has no impact but in

case if receiver fails then the packet is placed in receiver buffer so as soon as receiver

recovers it will get the message.

Thread: A thread is a section of code which is executing independently of others threads in a

same program. Java has a class Thread which is defined in java.lang package. Thread is the most

powerful feature that JAVA supports from other programming languages.

Multithreaded Client-Server Chat Application: In a multithreaded chat application a client

will use two threads to interact with standard input and with server. At server side there will be a

31
separate thread for each client. Whenever a client wants to establish a connection then a new

client thread is created. A multithreaded chat application will work like this:

 On the server side there will be a main thread which will continually listens to a given port.

 The client program client will send a request to establish a connection by sending the users

username.

 After establishing the connection, another thread is spawned to open a dialog box for

chatting with clients.

 At the server side for each connection there will be separate thread.

The Server program will maintain a list of all online clients and send that list to all clients who

are currently available.

 If a client logs out then the server will update its list and forward that updated list to all

online clients.

Deadlock: A deadlock situation will occur when two threads are circularly dependent on each

other e.g. thread1 is holding an object which is needed by the thread2 to complete its execution

and thread2 is holding the same object for which thread1 is waiting so both of them waiting for

each other to release the resource so in this condition a deadlock is created because thread1 and

thread2 are circularly dependent on each other.

Locks: While using resources threads can use locks to prevent from lock situation. Locks allow

java threads to quickly and easily communicate with each other. If a thread is holding a lock on

an object then no other thread can use that object.

32
In java each object has a lock by using synchronized keyword. Synchronized blocks can only be

executed by one thread at a time.

Synchronizing Thread: When two or more threads need access to a shared resource, there

should be a means through that resource will be used by only one thread at a time. The procedure

through which this synchronization is obtained is called thread synchronization.

The synchronized, a keyword in Java, is used to create a block of code referred to as a critical

section. The following is the syntax of synchronized statement in java:

synchronized(object) {

// statements to be synchronized

3.7 DATABASE DESIGN

How to create MySQL Database:

MySQL must be installed on the system and the port used for the MySQL configuration when

you install it is port 3306

---->>create a table in a new database create Database chatDatabase

use chatDatabase

create table users (name char(40), email char(25), user char(15), password char(15), random

char(10))

33
Make sure the MySQL is correctly setup, and then test it by running the DatabaseManager class.

It will open the USERS table and print details about it. If all fine (no error) then the database is

fine and Chat Server can connect to it. Start the server first, and then make sure the start button

on the server GUI is press (to establish connection between the server and the database). With

successfully connection established with the Database, the client can then request for

connection.

The following shows the user table created and stored in the MySQL database:

mysql> describe users

Table 1: MySQL User Table

+ + + + + + +

| Field | Type | Null | Key | Default | Extra |

+ + + + + + +

| name | char(40) | YES | | NULL | |

| email | char(25) | YES | | NULL | |

| user | char(15) | YES | | NULL | |

| password | char(15) | YES | | NULL | |

| random | char(10) | YES | | NULL | |

+ + + + + + +

5 rows in set (0.00 sec)

34
3.8 SYSTEM FLOW CHART

Server
Setup

Open Port and waiting


for request

No

Client sends requests to Requests?


connect to the server

Main
thread
Accept
Wait till confirmation
Received Create new thread
sending the information of
the request

User connection thread

Create new socket to


accept the connection
of the client

Send accept request

Send accept request Send/Receive Messages

Kill thread and


destroy Socket

Figure 3.6: Multithreading Flow Diagram

35
3.9 TOP DOWN DIAGRAM

User Interface Client Manager

Message Processor Message interpreter


Message
Maker
Sender Receiver

Sender
Receiver

Chat Client Chat Server

Figure 3.7: Client-Server Chat Application Architecture

Here Message Processor is used to interpret message from the user. Message Interpreter is used

to extract and then parse the received message. Message Maker is used to construct back the

message where as Client Manager is used to maintain the clients list, whereas sender and

receiver at both sides are used to interact with each other.

3.10 JUSTIFICATION OF THE NEW SYSTEM

This system implements hash function and salt for Data encryption which makes the system

greatly difficult to crack.

Another significance of this application is private chatting. This is where two users can chat in

private. The messages between the users are not displayed/seen in the general chat display text

field. The messages are displayed only within the private message display text field.

36
4.0 IMPLEMENTATION, TESTING AND INTEGRATION

4.1 CHOICE OF DEVELOPMENT TOOLS

Java became the chosen programming language for the client-server chat application because

Java application programming interfaces (API) provides the classes for creating sockets to

facilitate program communications over the network. Sockets are the endpoints of logical

connections between two hosts and can be used to send and receive data. Java treats socket

communications much as it treat input and output operations; thus programs can read from or

write to sockets as easily as they can read from or write to files.

MySQL became the chosen database for the client-server chat application as a result of the

following reasons:

1. The MySQL database server offers the best in scalability, sporting the ability to handle
intensely embedded applications by a footprint of merely 1MB to running huge data

storehouses handling terabytes of data. Its open source nature permits total customization for

adding unique necessities to the database server.

2. Either the planned application is a fast-speed business processing scheme or a large-volume


network site that provides a billion queries in 24 hours, MySQL is able to meet the most

challenging performance outlook of any scheme.

37
3. MySQL provides outstanding security features that guarantee total data protection. It offers
strong mechanisms for making sure that unauthorized clients have no access to the database

server.

4. The hallmarks of MySQL are steady availability and hard reliability.

5. MySQL is free and simple with low cost overhead. It is dependable and simple to maintain.

4.2 SYSTEM REQUIREMENTS

 Operating system: Linux (Ubuntu), Windows XP, Windows Vista, Windows 7,e.t.c

 Processor speed: 1.5 GHz and above

 Memory: 1 GB and above

 Hard disk drive space: 10GB

4.2.1 SOFTWARE REQUIREMENTS

The software requirements includes:-

 MySQL essential 5.0 and above.

 Java development kit (JDK) 6u11 and above.

4.2.2 HARDWARE REQUIREMENTS

In the course of the design, the software developed needed the following hardware for an

effective and efficient operation:

 Processor speed: 1.5 GHz and above

38
 Memory: 1 GB and above

 Hard disk drive space: 10GB

 E.G.A/V.G.A, a colored monitor.

 An uninterruptible power supply (UPS) units

 Standard keyboard and Mouse.

4.3 IMPLEMENTATION

As described in previous Chapters, in TCP based client server system, server will always start

first on some specific port and wait to listen to the client connection requests. So in this Chat

system firstly Chat Server is started in the following and waiting on port number 8080 for Chat

Client connection request and is successfully connected to the MySQL database. As shown in the

figure 4.1.

Figure 4.1: BAChatServer running

39
At the next step, server will accept the client connection request. So, the Chat Client window

which is connected to the Chat Server by using IP address 127.0.0.1 on local host and port

number 8080. As shown in the figure 4.2.

Figure 4.2: BAChatClient running

Before starting the chat, the client must be registered. To start the registration two options are

offered: option 1 - press “Yes” for already registered client to input login details; option 2 - press

“No” for new client to register. As shown 4.3:

40
Figure 4.3: BAChatClient Registration

After successful login to the Chat Server users can start chatting. All messages sent by the user

are displayed to all users until users start private messages. Sent messages are displays in the

display textfield.

The messages between the users are not displayed / seen in the general chat display textfield. The

messages are displayed only within the private message display textfield. As seen in the figure

4.4 below:

41
Figure 4.4: BAChatClient Room

The Database of Server, where database maintains record of all clients after confirming their

registration. All login details and messages are encrypted. This way information from the

Database is unreadable to whoever manages to access the Database. The original password of

every client is stored in the Database, in the form of computed hash values of the password and

salt (generated random number) that is stored in database.

42
Figure 4.5: Encrypted messages and message types sent by users

As soon as a user logs out, the server broadcast to all users that a user left the chat room and

remove the username from the list of users online. This displays the personal details of users

stored in the MySQL database. The five number of columns in the user table (as in the figure

below) represents: client names, clients email, client usernames, client passwords (Hash values),

and clients random generated number (Salt). Implementation of the SALT makes it extremely

difficult to compute the original password since the values stored in the database is the hash

values of the original password. In addition, to be able to get the values that represent the

original password, the system needs to add the random generated number to the hash values and

do some addition and subtraction.

43
Therefore, it is very clear from the above that even if the server security is compromised for any

reason, individuals’ passwords are secured.

Hash values Salt


Usernam

Client

Figure 4.6: MySQL Database

4.4 TESTING

Testing of software is a test conducted on a complete, integrated system to evaluate the system's

compliance with its specified requirements

4.4.1 UNIT TEST

This is the test carried out on the individual component or part of a system. Unit tests were

carried out on the Java program main classes.

44
 After compiling all the main classes of the java program, each class was tested and every

error found was corrected. The classes tested are as follows:

 BAChatClient.java

 BAChatServer.java

 ChatFrame.java

 ChatMessage.java

 ConnectionHandler.java

 ConnectionManager.java

 DatabaseManager.java

 Encryptor.java

 LoginDialog.java

 PrivateChatFrame.java

 RegisterDialog.java and

 ServerMainListener.java

 The tables created in the MySQL database were also tested and it worked properly as

expected.

4.4.2 SYSTEM TEST

System test falls within the scope of black box testing and does not require the knowledge of the

inner design of the code. In this case, software testing is any activity aimed at evaluating an

attribute or capability of a system and determining that it meets its required results. It is also the

process of executing a program or system with the intent of finding errors. Developing a good

and logically sound test plan is vital to developing a bug free software system. The table below

45
depicts the various tests carried out, result of the tests and conclusions which were based on the

results.

The system test was carried out by integrating all the different Java classes together and linking

them up with the data base. After this was done, the system was initialised and the Server chat

application was started, the client chat application was also initialised. All the other classes were

tested and they met the expected output.

4.5 INTEGRATION

To implement the application on a real network, MySQL must be installed on the server host and

port used for the MySQL configuration when you install it should be port 3306 and database

password = w1127449 and database Server IP = localhost.

Java development kit (JDK) must also be installed all the source codes used be compiled without

error. Thereafter, the user can start and use the same server IP address and Port number to be

able to establish connection with the server.

46
5.0 SUMMARY, RECOMMENDATIONS AND CONCLUSION

5.1 SUMMARY

Client-server model is used to communicate over the network where the server is the system that

provides services and clients are the systems that want to use these services to communicate with

other client systems in the network. In this application, at server side a thread is created that

receives numerous clients’ requests. It also contains a list in which Client’s name and IP

addresses are stored. After that, it broadcasts the list to all the users who are currently in chat

room and when a client logs out then server deletes that particular client from the list, updates the

list and then broadcast the list to all available clients. A client firstly must have to register itself

by sending username to the server and should have to start the thread so that the system can get

the list of all available clients. Then any of two registered clients can communicate with each

other.

5.2 LIMITATIONS

Some drawbacks of the Client-Server Chat are as follows:

 Time Constraint

 Financial Constraint.

 In case of server fails then the users also suffers.

 A lost password is irrecoverable.

47
 As the server receives as many requests from clients so there is a chance that server can
become congested and overloaded.

5.3 RECOMMENDATIONS

Instead of starting a new thread for each task to perform concurrently, the task can be passed to a

thread pool. Thread Pools are useful when you need to limit the number of threads running in an

application at the same time. There is a performance overhead cost linked with beginning a new

thread, because each thread allocates some memory for its stack. This could not be implemented

in this application because of time limit. Another suggestion for future works is the use of Java

technology newest flavor of TCP Reno. This is because of its light weight and extreme advance

features to overcome the flaws of the traditional Transmission Control Protocol.

I recommend that for future works, Thread pool should be used instead of starting new thread for

each task. TCP Reno should also be implemented in the future works due to its benefits as

mentioned above.

5.4 BILL OF SCIENTIFIC MEASUREMENT AND EVALUATION

(BEME)

RATE TOTAL
S/N COMPONENTS QUANTITY
(N) (N)

1 Data Subscription (MTN) 10GB 5,000 5,000

48
Journal: The Socket Programming and
2
Software Design for Communication
1 2,500 2,500
Based on Client-Server by Ming Xue;
Changjun Zhu

3
Consultation fee for Java Socket
10,000
programming tutorial

4
Logistics 5,000

5
Miscellaneous expenses 7,500

TOTAL 31,000

5.5 CONCLUSION

A secured chat application has been developed with TCP. TCP is a connection-oriented protocol,

so once the connection is established there is no need to send socket address again and again. It

is reliable, it guarantees that each packet will arrive and also guarantees that packets will be in

the right order.

This project used MySQL for its database to make information in the database secure. The

personal details and messages including the private messages in the Database are encrypted

using encryptor (one of the security facilities available in the MySQL. As mentioned earlier,

MySQL became the obvious choice for the implementation of Secured Java Client-Server Chat

Application for the reasons that: MySQL provide secure connections between MySQL clients

49
and the server using the Secure Sockets Layer (SSL) protocol (for the database) to provide

secure data communication.

The project implements hash function with the password before the encryption and then stored in

the Database; this application also uses random generated numbers (salt) that is calculated

together with the password hash values and stored in the Database. As a result, even if the

database is compromised, the salt added to hash values makes it harder to compute the original

password. When a random salt is used with the hash function, it significantly increases the

strength of encrypting passwords thus makes cracking greatly more difficult. Therefore, makes

the chat application server reliable and more secured.

Real network connection is another achievement of this application implementation.

Another accomplishment of this application is private chatting. This is where two users can chat

in private. The messages between the users are not displayed / seen in the general chat display

textfield. The messages are displayed only within the private message display textfield. It shows

and keeps history of the private messages.

As mentioned earlier, this application has been developed placing security of the network as

priority, thus, look in details all aspect of network programming lapses, especially client-server

chatting system.

50
REFERENCES

Bhatt, D.V.; Schulze, S.; Hancke, G.P.; "Secure Internet access to gateway using secure socket

layer," vol.55, no.3, pp.793-800, June 2006

Client-server Chat [http://jerome.jouvie.free.fr/Java/Network/Tutorials/Tutorial2.php]

(01/07/2010).

Ming Xue; Changjun Zhu;"The Socket Programming and Software Design for Communication

Based on Client/Server," PACCS '09. Pacific-Asia Conference on, vol., no., pp.775-777,

16-17 May 2009

Multithreaded Client/Server Application [http://www.ase.md/~aursu/ClientServerThreads.html]

Shukla, A.; Brecht, Tim.;"TCP Connection Management Mechanisms for Improving Internet

Server Performance,"1st IEEE Workshop on, vol., no., pp.1-12, 13-14 Nov. 2006

Zhenxing Liu; Lallie, H.S.; Lu Liu; Yongzhao Zhan; Kaigui Wu; , "A hash-based secure

interface on plain connection.vol., no., pp.12-39, 17-19 Aug.2011

51
52

You might also like