You are on page 1of 22

MULTI-THREADED CHAT APPLICATION IN JAVA

A case study report submitted in partial fulfillment of the subject

INTEGRATED DEVELOPMENT ENVIRONMENT


IN
B.TECH . IV YEAR VII SEMISTER
OF
COMPUTER SCIENCE AND ENGINEERING
Submitted by
A.Chamanthi (121710305004)
B.Pavani (121710305008)
K.Pavan Krishna Chand (121710305027)
M.Vishnu Vipul (121710305057)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


GITAM INSTITUTE OF TECHNOLOGY
GITAM
(Deemed to be University)
VISAKHAPATNAM
DECEMBER 2020

1
INDEX

2
1. INTRODUCTION

1.1. INTEGRATED DEVELOPMENT ENVIRONMENT


An IDE, or Integrated Development Environment, enables programmers to consolidate the
different aspects of writing a computer program.

IDEs increase programmer productivity by combining common activities of writing software


into a single application: editing source code, building executables, and debugging.

1.2. ADVANTAGES OF IDE:


 Using IDE will cost you less time and effort .
 Navigation is made easier.
 Auto completion- one of the best features , you don’t have to remember all.
 4.Refactoring
 Error debugging is easy , you can easily navigate to Error line.
 6.All files can be viewed and managed at same screen.
 7.Organizing you imports.
 8.Downloading requires packages at ease.

2. ECLIPSE

The Eclipse IDE has a very long development history. In November 2001, IBM created
the Eclipse Project to implement a Java-based IDE that supports development of embedded
Java applications. The initial version of Eclipse derives from Visual Age - a multi-
programming language IDE from IBM.
In January 2004, the Eclipse Foundation was established as an independent not-for-profit
corporation to transparently develop the Eclipse Project as an open and vendor-neutral
product.
Originally created for developing a Java IDE, the Eclipse Foundation is now developing a
wide range of development tools that support many programming languages: C/C++, PHP,
Javascript, Python, Rust…However Eclipse is best known as the most widely used IDE for
Java development.
Because the Eclipse Foundation releases many packages for different programming
languages and different domains, in this course the name Eclipse or Eclipse IDE refers to the
package Eclipse IDE for Java EE Developers. And as Java programmer, you use this
package most of the time.

3
For me, I started using Eclipse in 2004 - Eclipse 3.0 with JDK 1.4.
Eclipse is free and open-source, which means you can use it at no cost and access its source
code if needed. Today, Eclipse is the most widely used IDE for developing Java applications,
with millions of programmers using every day. The homepage of Eclipse is eclipse.org.
 

2.1. PROGRAMMING LANGUAGE IS USED TO MAKE


ECLIPSE

Eclipse IDE is written mostly in Java and some native parts are written in C/C++. Eclipse can
run on major operating systems like Windows, Mac and Linux. So if you are using Eclipse
IDE, you are actually running a Java application!
   

2.2. VERSIONS OF ECLIPSE

Eclipse has a long history of development so it has been evolving over many versions.
Eclipse uses interesting naming for its versions, mostly based on astronomy scheme: Juno,
Kepler, Luna, Mars, Neon, Oxygen, Photon…and the latest version uses different naming
scheme, i.e. month-year format: Eclipse 2018-09.
Though evolving over many versions, the key concepts, structure and working of the IDE
remain unchanged. Mostly new features and improvements were added.

2.3. ADVANTAGES
1. It is free and open source.
2. Industrial level of development
3. It supports many other languages other than JAVA.
4. Framework integration like Junit and TestNG and other plugins can be done
easily.
5. Since Eclipse tools are open source, they are quickly updated with the latest
technology that can be integrated into existing code.

2.4. DOWNLOADING AND INSTALLATION OF ECLIPSE


4
2.4.1. DOWNLOADING
You can download eclipse from http://www.eclipse.org/downloads/. The download page lists
a number of flavors of eclipse.

The capabilities of each packaging of eclipse are different. Java developers typically use
Eclipse Classic or Eclipse IDE for developing Java applications.
The drop down box in the right corner of the download page allows you to set the operating
system on which eclipse is to be installed. You can choose between Windows, Linux and
Mac. Eclipse is packaged as a zip file.

2.4.2. INSTALLING ECLIPSE


To install on windows, you need a tool that can extract the contents of a zip file. For
example you can use −

 7-zip
 PeaZip
 IZArc
Using any one of these tools, extract the contents of the eclipse zip file to any folder of your
choice.

5
2.5. LAUNCHING ECLIPSE
On the windows platform, if you extracted the contents of the zip file to c:\, then you can
start eclipse by using c:\eclipse\eclipse.exe
When eclipse starts up for the first time it prompts you for the location of the workspace
folder. All your data will be stored in the workspace folder. You can accept the default or
choose a new location.

If you select "Use this as the default and do not ask again", this dialog box will not come up
again. You can change this preference using the Workspaces Preference Page.

6
2.6. PARTS OF AN ECLIPSE WINDOW
The major visible parts of an eclipse window are −

 Views
 Editors (all appear in one editor area)
 Menu Bar
 Toolbar
An eclipse perspective is the name given to an initial collection and arrangement of views
and an editor area. The default perspective is called java. An eclipse window can have
multiple perspectives open in it but only one perspective can be active at any point of time.
A user can switch between open perspectives or open a new perspective. A perspective
controls what appears in some menus and tool bars.

A perspective has only one editor area in which multiple editors can be open. The editor area
is usually surrounded by multiple views. In general, editors are used to edit the project data
and views are used to view the project metadata. For example the package explorer shows
the java files in the project and the java editor is used to edit a java file.

7
The eclipse window can contain multiple editors and views but only one of them is active at
any given point of time. The title bar of the active editor or view looks different from all the
others.
The UI elements on the menu bar and tool bar represent commands that can be triggered by
an end user.

Using Multiple Windows

Multiple Eclipse Windows can be open at the same time. To open a new window, click on
the Windows menu and select the New Window menu item.
Each window can have a different perspective open in them. For example you could open
two Eclipse windows one in the Java perspective and the other in the Debug perspective.
The window showing the Java perspective can be used for editing the java code and the
window showing the debug perspective can be used for debugging the application being
developed.

Typical Eclipse Menus

The typical menus available on the menu bar of an Eclipse window are −

Sr.N Menu Name & Description


o

File
1 The File menu allows you to open files for editing, close editors, save editor content and rename
files. Among the other things, it also allows you to import and export workspace content and
shutdown Eclipse.

Edit
2
The Edit menu presents items like copy & paste.

Source
3
The Source menu is visible only when a java editor is open. It presents a number of useful menu
items related to editing java source code.

Navigate
4
The Navigate menu allows you to quickly locate resources and navigate to them.

5 Search

8
The Search menu presents items that allow you to search the workspace for files that contain
specific data.

Project
6
The menu items related to building a project can be found on the Project menu.

Run
7
The menu items on the Run menu allow you to start a program in the run mode or debug mode. It
also presents menu items that allow you to debug the code.

Window
8
The Window menu allows you to open and close views and perspectives. It also allows you to
bring up the Preferences dialog.

Help
9
The Help menu can be used to bring up the Help window, Eclipse Marketplace view or Install new
plug-ins. The about Eclipse menu item gives you version information.

3. JAVA

3.1. WHAT IS JAVA?


Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since
Oak was already a registered company, so James Gosling and his team changed the Oak
name to Java.

3.2. APPLICATIONS OF JAVA


According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.

9
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

3.3. TYPES OF JAVA APPLICATIONS


There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based


applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used
for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called


enterprise application. It has advantages of the high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.

3.4. FEATURES OF JAVA

The primary objective of Java programming language creation was to make it portable,


simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of
Java are also known as java buzzwords.

10
A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

11
4. MULTI-THREADED CHAT APPLICATION

4.1. SERVER SIDE PROGRAMMING


A simple date time server was created which handled multiple user requests at the same time using
threading. It explains the basic concepts of threading in network programming. The same concepts can
be used with very slight modification to extend the above idea and create a chatting application similar
to facebook messenger, whatsapp etc.
The following description covers the implementation of such an application with a detailed explanation,
limitations, and their solutions.

Server Side Programming(Server.java)


 Server class : The main server implementation is easy and similar to the previous
article. The following points will help understand Server implementation :
1. The server runs an infinite loop to keep accepting incoming requests.
2. When a request comes, it assigns a new thread to handle the
communication part.
3. The sever also stores the client name into a vector, to keep a track of
connected devices. The vector stores the thread object corresponding to
the current request. The helper class uses this vector to find the name of
recipient to which message is to be delivered. As this vector holds all the
streams, handler class can use it to successfully deliver messages to
specific clients.
4. Invoke the start() method.
 
 ClientHandler class : Similar to previous article, we create a helper class for handling
various requests. This time, along with the socket and streams, we introduce a name
variable. This will hold the name of the client that is connected to the server. The
following points will help understand ClientHandler implementation :
1. Whenever the handler receives any string, it breaks it into the message
and recipient part. It uses Stringtokenizer for this purpose with ‘#’ as the
delimiter. Here it is assumed that the string is always of the format:
message # recipient
2. It then searches for the name of recipient in the connected clients list,
stored as a vector in the server. If it finds the recipients name in the
clients list, it forwards the message on its output stream with the name of
the sender prefixed to the message.

// Java implementation of Server side


// It contains two classes : Server and ClientHandler
// Save file as Server.java

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

12
// Server class
public class Server
{

// Vector to store active clients


static Vector<ClientHandler> ar = new Vector<>();

// counter for clients


static int i = 0;

public static void main(String[] args) throws IOException


{
// server is listening on port 1234
ServerSocket ss = new ServerSocket(1234);

Socket s;

// running infinite loop for getting


// client request
while (true)
{
// Accept the incoming request
s = ss.accept();

System.out.println("New client request received : " + s);

// obtain input and output streams


DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());

System.out.println("Creating a new handler for this client...");

13
// Create a new handler object for handling this request.
ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);

// Create a new Thread with this object.


Thread t = new Thread(mtch);

System.out.println("Adding this client to active client list");

// add this client to active clients list


ar.add(mtch);

// start the thread.


t.start();

// increment i for new client.


// i is used for naming only, and can be replaced
// by any naming scheme
i++;

}
}
}

// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;

14
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos)
{
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
}

@Override
public void run() {

String received;
while (true)
{
try
{
// receive the string
received = dis.readUTF();

System.out.println(received);

if(received.equals("logout")){
this.isloggedin=false;
this.s.close();
break;
}

// break the string into message and recipient part

15
StringTokenizer st = new StringTokenizer(received, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();

// search for the recipient in the connected devices list.


// ar is the vector storing client of active users
for (ClientHandler mc : Server.ar)
{
// if the recipient is found, write on its
// output stream
if (mc.name.equals(recipient) && mc.isloggedin==true)
{
mc.dos.writeUTF(this.name+" : "+MsgToSend);
break;
}
}
} catch (IOException e) {

e.printStackTrace();
}

}
try
{
// closing resources
this.dis.close();
this.dos.close();

}catch(IOException e){
e.printStackTrace();
}
}

16
}

Output:
New client request received : Socket[addr=/127.0.0.1,port=61818,localport=1234]
Creating a new handler for this client...
Adding this client to active client list
New client request received : Socket[addr=/127.0.0.1,port=61819,localport=1234]
Creating a new handler for this client...
Adding this client to active client list

Limitations:
Although the above implementation of server manages to handle most of the scenarios,
there are some shortcomings in the approach defined above.
 One clear observation from above programs is that if the number of
clients grew large, the searching time would increase in the handler
class. To avoid this increase, two hash maps can be used. One with name
as the key, and index in active list as the value. Another with index as
key, and associated handler object as value. This way, we can quickly
look up the two hashmaps for matching recipient. It is left to the readers
to implement this hack to increase efficiency of the implementation.
 Another thing to notice is that this implementation doesn’t work well
when users disconnect from the server. A lot of errors would be
thrown because disconnection is not handled in this implementation. It
can easily be implemented as in previous basic TCP examples. It is also
left for the reader to implement this feature in the program.

4.2. CLIENT SIDE PROGRAMMING


This section gives the implementation of client program for the multi-threaded chat application.
Till now all examples in socket programming assume that client first sends some information
and then server or other clients responds to that information.
In real world, this might not be the case. It is not required to send someone a message in order
to be able to receive one. A client should readily receive a message whenever it is delivered to
it i.e sending and receiving must be implemented as separate activities rather than
sequential.
There is a very simple solution which uses threads to achieve this functionality. In the client
side implementation we will be creating two threads:

1-SendMessage : This thread will be used for sending the message to other clients. The
working is very simple, it takes input the message to send and the recipient to deliver to. Note
that this implementation assumes the message to be of the format message # recipient, where
recipient is the name of the recipient. It then writes the message on its output stream which is
connected to the handler for this client. The handler breaks the message and recipient part and
deliver to particular recipient. Lets look at how this thread can be implemented.

Thread sendMessage = new Thread(new Runnable() {

17
@Override
public void run() {
while (true) {

// read the message to deliver.


String msg = sc.nextLine();
try {

// write on the output stream


dos.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});

2-readMessage : A similar approach is taken for creating a thread for receiving the messages. When
any client tries to write on this clients input stream, we use readUTF() method to read that message.
The following snippet of how this thread is implemented is shown below-
Thread readMessage = new Thread(new Runnable() {

@Override
public void run() {

while (true) {
try {

// read the message sent to this client


String msg = dis.readUTF();
System.out.println(msg);
} catch (IOException e) {

e.printStackTrace();
}
}
}
});

18
The remaining steps of client side programming are similar to previous examples. A brief
explanation is as follows –
1. Establish a Socket Connection
2. Communication
Communication occurs with the help of the readMessage and sendMessage
threads. Separate threads for reading and writing ensures simultaneous sending
and receiving of messages.
// Java implementation for multithreaded chat client
// Save file as Client.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client


{
final static int ServerPort = 1234;

public static void main(String args[]) throws UnknownHostException, IOException


{
Scanner scn = new Scanner(System.in);

// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");

// establish the connection


Socket s = new Socket(ip, ServerPort);

// obtaining input and out streams


DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());

// sendMessage thread

19
Thread sendMessage = new Thread(new Runnable()
{
@Override
public void run() {
while (true) {

// read the message to deliver.


String msg = scn.nextLine();

try {
// write on the output stream
dos.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});

// readMessage thread
Thread readMessage = new Thread(new Runnable()
{
@Override
public void run() {

while (true) {
try {
// read the message sent to this client
String msg = dis.readUTF();
System.out.println(msg);
} catch (IOException e) {

20
e.printStackTrace();
}
}
}
});

sendMessage.start();
readMessage.start();

}
}

Output :
From client 0 :
hello#client 1
client 1 : heya
how are you#client 1
client 1 : fine..how about you
logout
From client 1 :
client 0 : hello
heya#client 0
client 0 : how are you
fine..how about you#client 0
logout

Important points :
 To send a message from any client, type the message, followed by a “#” and
then the name of the recipient client. Please note that this implementation gives
names as “client 0”, “client 1″….”client n” and so carefully names must be
appended int the end. After that press Enter key.
 Once a message is sent, the handler for this client will receive the message and it
will be delivered to the specified client.
 If any client sends a message to this client, the readMessage thread will
automatically print the message on the console.
 Once a client is done with chatting, he can send a “logout” message without any
recipient name so that server would know that this client has logged off the
system. It is recommended to send a logout message before closing the terminal
for the client to avoid any errors.

21
5. CONCLUSION

This case study is a thorough surveyed and researched with the help of my group members.
We learned the importance of IDE, especially the importance and advantages of ECLIPSE.
We developed an application on ECLIPSE IDE using JAVA programming language.

22

You might also like