You are on page 1of 37

Chapter 1: Introduction

1.1 Needs & Objective

Needs
A. To make the interaction between users easy and effective via socket programming
in java.
B. To communicate among different users working on same local area network.

Objective
A. Implement Graphical user interface in java using swing.
B. Implement socket programming in java.
C. Implement multithreading with GUI in java and socket programming.
D. Fast connection between users on network.
E. Enhancing user efficiency.
F. Creates connection by making it easy for others to plug into the platform.

1.2 Methodology
The Methodology for the “Chat Application” is as follows:
 Designing the Algorithm for the project.
 Implementing the code in JAVA.
 Designing a Graphical User Interface in JAVA.
 Backend using Network Programming via sockets in JAVA.

1
1.3 Software Used

Visual Studio Code

Visual Studio Code is a lightweight but powerful source code editor which runs on your
desktop and is available for Windows, macOS and Linux. It comes with built-in support
for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other
languages (such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and
Unity).
Visual Studio Code is a streamlined code editor with support for development
operations like debugging, task running, and version control. It aims to provide just the
tools a developer needs for a quick code-build-debug cycle and leaves more complex
workflows to fuller featured IDEs, such as Visual Studio IDE.
The Java support in Visual Studio Code is provided through a wide range of extensions.
By installing extensions, you can have a lightweight and performant code editor which
also supports many popular Java development tools. VS Code provides essential
language features such as code completion, refactoring, linting, formatting, and code
snippets along with convenient debugging and unit test support. VS Code can also
integrate with tooling and frameworks such as Maven, Tomcat, Jetty, and Spring Boot.
Leveraging the power of Visual Studio Code, Java developers get an excellent tool for
both quick codes editing and also the full debugging and testing cycle. It's a great choice
for your Java work if you're looking for a tool which:

 Is fast and lightweight, free, and open source


 Supports multiple, or all the programming languages you use
 Helps start your Java journey without installing and learning a complex IDE
 Provides great micro services support including popular framework, container
tooling and cloud integration
 Improves your productivity through smartness and collaboration features

2
Java Development Kit (JDK)

The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc) and other tools needed in Java development.

The JDK includes a variety of tools and utilities that perform a variety of tasks, which
include compiling source code into bytecode, packaging applications, spinning up Java
virtual machines (JVMs) and managing the runtime environment of Java applications.

NetBeans IDE
NetBeans IDE is the official IDE for Java 8. With its editors, code analyzers, and
converters, you can quickly and smoothly upgrade your applications to use new Java 8
language constructs, such as lambdas, functional operations, and method references.

Batch analyzers and converters are provided to search through multiple applications at
the same time, matching patterns for conversion to new Java 8 language constructs.

With its constantly improving Java Editor, many rich features and an extensive range
of tools, templates and samples, NetBeans IDE sets the standard for developing with
cutting edge technologies out of the box.

Some Features:
 Fast & Smart Code Editing - The NetBeans Editor indents lines, matches words
and brackets, and highlights source code syntactically and semantically. It lets you
easily refactor code, with a range of handy and powerful tools, while it also
provides code templates, coding tips, and code generators.

3
 Easy & Efficient Project Management - NetBeans IDE provides different views
of your data, from multiple project windows to helpful tools for setting up your
applications and managing them efficiently, letting you drill down into your data
quickly and easily, while giving you versioning tools via Subversion, Mercurial,
and Git integration out of the box.

 Rapid User Interface Development - Design GUIs for Java SE, HTML5, Java EE,
PHP, C/C++, and Java ME applications quickly and smoothly by using editors and
drag-and-drop tools in the IDE.

 Support For Multiple Languages - NetBeans IDE offers superior support for C/C++
and PHP developers, providing comprehensive editors and tools for their related
frameworks and technologies.

 Cross Platform Support - NetBeans IDE can be installed on all operating systems
that support Java, from Windows to Linux to Mac OS X systems.

 Rich Set of Community Provided Plugins - The NetBeans community is large and
active; many users are developing new plugins all the time because NetBeans IDE
is extensible and has well-documented APIs

4
1.4 About Organization

FIG 1.1

TECHAVERA is a certified ISO 9001:2008, technology service provider and


training,development, consultancy organization. The soul mission of founders is to
facilitate the education, research and development program; all under one roof. In
a very short span of time our team has successfully delivered the impactful service
to more than 200 colleges, including all the NITs. All over the India, with our 6
centers, we are renowned for our own manufacturing unit and unique content.
TECHAVERA is moving ahead with an ideology where practical and theory are
equally emphasized. In the vast growing ‘Technical Era’ we are rising with a
mission to expand the set boundaries of the ‘techie-brains’ to Explore, Invent and
Innovate!

5
1.5 COMPANY VISION
TECHAVERA has a vibrant yet straightforward purpose – To Develop Better.
We breathe and live the philosophy that every client matters and the results are
everything.
We aim to compete with established IT firms in the market by delivering beneficial
strategies and successful business practices. Our belief is client satisfaction is the long-
term way for our business to grow.

COMPANY VALUES
o Passion for technology
o Constructive self-criticism, self-improvement
o Pursuit of Excellence
o Discovering advanced ways to meet & exceed expectations
o Openness & respect
o Integrity & honesty

COURSES
o Summer Industrial Training Program
o Winter Industrial Training Program
o Regular Training

CONTACT DETAILS
Address
3rd Floor, Om Complex, Naya Bans, Sector 15, Noida, Uttar Pradesh 2013013rd
Floor, Om Complex, Naya Bans, Sector 15, Noida, Uttar Pradesh 201301
Phone No.
085068 88288
Online Support
http://www.techaveranoida.in

6
Chapter 2: Project Design

2.1 Introduction
IC has become a day-to-day utility for everyone. The reason for choosing IC is that it
provides a good scope for beginners to implement a network-based system. IC is a type
of chatting application that provides text-transmission over the Internet. IC operates in
a similar way as that of a LAN Messenger over a Local Area Network. Messages are
transmitted between two parties i.e. The sender and the receiver, it can also be between
more than two parties (group chatting). The messages transmitted are bi-directional in
nature. Messaging applications also use push technology to provide real-time
transmission of messages as they are composed, character by character. The advanced
IC applications which are available now also offer file transfer, voice calls, video calls.
The two protocols applied for the system are Transport Control Protocol (TCP) and
User Datagram Protocol (UDP). TCP is for control message and UDP is for chat
messaging.
Chatting applications enables us to stay in connected anytime, anywhere from any part
of the world. There are many applications which provides chat services, the most
popular among them are WhatsApp, Facebook messenger, yahoo IM, emails etc. IC
applications have evolved from being just another application to send messages. The
latest IC applications have features such as transfer of different types of files, video
chatting, group chat etc. The common disadvantage is that these applications restrict
the size of the files being transferred. Thus, in IC we have implemented chatting with
unlimited data transfer without any size restriction.

2.2 Process Selection


We chose Java because of its following features:
Simple
According to Sun, Java language is simple because :
A. syntax is based on C++ (so easier for programmers to learn it after C++).

7
B. Removed many confusing and/or rarely used features e.g., explicit pointers, operator
overloading etc.
C. No need to remove unreferenced objects because there is Automatic Garbage
Collection in java
Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour. Object-oriented programming
(OOPs) is a methodology that simplify software development and maintenance by
providing some rules.

Fig 2.1 OOP concept

8
Secured

Java is secured because:

A. No explicit pointer
B. Java Programs run inside virtual machine sandbox
C. Class loader: adds security by separating the package for the classes of the local file
system from those that are imported from network
D. Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
E. Security Manager: determines what resources a class can access such as reading and
writing to the local disk.

9
Fig 2.3 Java Security[6]

Architecture-neutral

There is no implementation dependent features e.g. size of primitive types is fixed. In


C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory
for both 32 and 64 bit architectures. Hence, this property also makes Java Portable.

10
2.3 BASICS OF JAVA

Overview Of Java
Java is a platform independent, more powerful, secure, high performance, multithreaded
programming language. Here we discuss some points related to java.

Define JRE
The Java Runtime Environment (JRE) is part of the Java Development Kit (JDK). It
contains set of libraries and tools for developing java application. The Java Runtime
Environment provides the minimum requirements for executing a Java application.

Define JVM
JVM is set of programs developed by sun Micro System and supplied as a part of jdk
for reading line by line of byte code and it converts into native understanding form of
operating system. Java language is one of the compiled and interpreted programming
language.

Garbage Collector
Garbage Collector is the system Java program which runs in the background along with
regular Java program to collect un-Referenced (unused) memory space for improving
the performance of our applications.

Define an API
An API (Application Programming Interface) is a collection of packages, a package
is the collection of classes, interfaces and sub-packages. A sub-package is a collection
of classes interfaces and sub sub packages etc.

Java programming is containing user friendly syntax so that we can develop effective
application s. in other words if any language is providing user friendly syntax, we can
develop error free applications.

11
Definition of JIT

JIT is the set of programs developed by SUN Micro System and added as a part of JVM,
to speed up the interpretation phase

Features Of JAVA

Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features are;

FIG 2.4 Java Classpath Setting

2.3.1 Path Variable

Path variable is set for providing path for all java tools like java, javac, javap, javah, jar,
appletviewer which are use in java programming. These all tools are available
in bin folders so we set path upto bin folders.

12
2.3.2 Classpath Variable

Classpath variable is set for providing path for predefined java classes which is used in
our application. All classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.

2.3.3 Steps For CompilingAnd Executing Programs

The following sequence of steps represented in the diagram use compiling the java
program and executing the java programs.

FIG 2.5 Compiling Diagam

13
2.4 Studying JAVA SWING

Work Flow Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.

Java swing components are platform-independent.

Swing components are lightweight.

Swing supports pluggable look and feel .

Swing provides more powerful components such as tables, lists, scroll

panes, color chooser, tabbed pane etc.

Swing follows MVC.

14
2.4.1 Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Fig-2.6 Hierarchy of Java Swing classes

FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();

//creating instance of JFrame

JButton b=new JButton("click"); //creating instance of JButton


b.setBounds(130,100,100, 40);

15
//x axis, y axis, width, height

f.add(b); //adding button in JFrame

f.setSize(400,500); //400 width and 500 height

f.setLayout(null); //using no layout managers

f.setVisible(true); //making the frame visible

Output-

Fig-2.7 Swing Output

16
2.5 MULTITHREADING IN JAVA

Java is a multi-threaded programming language which means we can develop


multithreaded program using Java. A multi-threaded program contains two or more
parts that can run concurrently and each part can handle a different task at the same
time making optimal use of the available resources specially when your computer has
multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application
into individual threads. Each of the threads can run in parallel. The OS divides
processing time not only among different applications, but also among each thread
within an application.
Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

2.5.1 Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.

Fig-2.8 Multithreading life Cycle

17
Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born thread.

 Runnable − after a newly born thread is started, the thread becomes runnable.
A thread in this state is executing its task.

 Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.

 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.

 Terminated (Dead) − A runnable thread enters the terminated state when it


completes its task or otherwise terminates. Thread Priorities Every Java thread has a
priority that helps the operating system determine the order in which threads are
scheduled.


Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot
guarantee the order in which threads execute and are very much platform dependent.
Create a Thread by Implementing a Runnable Interface If your class is intended to be
executed as a thread then you can achieve this by implementing a Runnable interface.

18
You will need to follow three basic steps −

Step 1- As a first step, you need to implement a run() method provided by a Runnable
interface. This method provides an entry point for the thread and you will put your
complete business logic inside this method.

Following is a simple syntax of the run() method − public void run( )

Step 2- As a second step, you will instantiate a Thread object using the following
constructor − Thread(Runnable threadObj, String threadName);

Where threadObj is the instance of the class that implements the Runnable interface
and threadName is the name given to the new thread.

Step 3- Once a Thread object is created, you can start it by calling start() method,
which executes a call to run( ) method. Following is a simple syntax of start()

method − void start();

Example

Here is an example that creates a new thread and starts running it −

class RunnableDemo implements Runnable {

private Thread t;

private String threadName;

RunnableDemo( String name) {

19
threadName = name;

System.out.println("Creating " + threadName );

public void run() {

System.out.println("Running " + threadName );

try {
for(int i = 4; i > 0; i--) {

System.out.println("Thread: " + threadName + ", " + i);// Let the thread


sleep
Thread.sleep(50);
}

}
catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start () {

20
System.out.println("Starting " + threadName );

if (t == null) {

t = new Thread (this, threadName);

t.start ();

}}

public class TestThread {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");


R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}

This will produce the following result −

Output

Creating Thread-1
Starting Thread-1

21
Creating Thread-2
Starting Thread-2

Running Thread-1

Thread: Thread-1, 4

Running Thread-2

Thread: Thread-2, 4

Thread: Thread-1, 3

Thread: Thread-2, 3
Thread: Thread-1, 2

Thread: Thread-2, 2

Thread: Thread-1, 1

Thread: Thread-2, 1

22
2.6 JAVA NETWORKING

The term Network programming refers to writing programs that execute across multiple
devices (Computers), in which the devices are all connected to each other using
networks. The Java net package of the J2se API contains a collection of classes and
interfaces that provide the low-level communication details, allowing you to write
programs that focus on solving problem at hand.

The java net package provides support for the two common network protocols.

1. The java.net package provides support for the two common


network protocols

 TCP- TCP stands for transmission control protocol, which allows


for reliable communication between two applications. TCP is
typically used over the Internet Protocol, which is referred to as
TCP/IP.

 UDP (User Datagram Protocol)- UDP stands for User Datagram
Protocol, a connection-less protocol that allows for packets of data to
be transmitters between applications.

2. This chapter gives a good understanding on the following two


subjects −

 URL Processing- This would be covered separately. Click here to


learn about URL Processing in java language.

 Socket Programming- Sockets provide the communication
mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to

23
connect that socket to a server. When the connection is made, the server
creates a socket object on its end of the communication. The client and
the server can now communicate by writing to and reading from the
socket.

2.6.1 Socket Overview

A socket is an object that represents a low level access point to the IP stack. This socket
can be opened or closed or one of a set number of intermediate states. A socket can
send and receive data down disconnection. Data is generally sent in blocks of few
kilobytes at a time for efficiency; each of these block are called a packet.

All packets that travel on the internet must use the Internet Protocol. This means that
the source IP address, destination address must be included in the packet. Most packets
also contain a port number. A port is simply a number between 1 and 65,535 that is
used to differentiate higher protocols. Ports are important when it comes to
programming your own network applications because no two applications can use the
same port.

Packets that contain port numbers come in two flavors: UDP and TCP/IP. UDP has
lower latency than TCP/IP, especially on startup. Where data integrity is not of the
utmost concerned, UDP can prove easier to use than TCP, but it should never be used
where data integrity is more important than performance; however, data sent by UDP
can sometimes arrive in the wrong order and be effectively useless to the receiver.
TCP/IP is more complex than UDP and has generally longer latencies, but it does
guarantee that data does not become corrupted when travelling over the internet. TCP
is ideal for file transfer, where a corrupt file is more unacceptable than a slow
download; however, it is unsuited to internet radio, where the odd sound out of place
is more acceptable than long gaps of silence.

24
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.

Network: This refers to a system where 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).

25
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.

26
Chapter 3: Implementation

A socket is one endpoint of a two-way communication link between two programs


running on the network. The socket is bound to a port number so that the TCP layer
can identify the application that data is destined to be sent.

In java socket programming example tutorial, we will learn how to write java socket
server and java socket client program. We will also learn how server client program
read and write data on the socket.

java.net.Socket and java.net.ServerSocket are the java classes that implements


Socket and Socket server.

3.1 Client Side Programming

Establish a Socket Connection


To connect to other machine we need a socket connection. A socket connection means
the two machines have information about each other’s network location (IP Address) and
TCP port.The java.net.Socket class represents a Socket. To open a socket:

Socket socket = new Socket(“127.0.0.1”, 5000)

 First argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost,


where code will run on single stand-alone machine).
 Second argument – TCP Port. (Just a number representing which application to run
on a server. For example, HTTP runs on port 80. Port number can be from 0 to
65535)

Communication
To communicate over a socket connection, streams are used to both input and output the
data.

27
Closing the connection
The socket connection is closed explicitly once the message to server is sent.
In the program, Client keeps reading input from user and sends to the server until
“Over” is typed.

Java Implementation
// A Java program for a Client
import java.net.*;
import java.io.*;

public class Client


{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;

// constructor to put ip address and port


public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");

// takes input from terminal


input = new DataInputStream(System.in);

// sends output to the socket


out = new DataOutputStream(socket.getOutputStream());

28
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}

// string to read message from input


String line = "";

// keep reading until "Over" is input


while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}

// close the connection


try
{
input.close();

29
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
Client client = new Client("127.0.0.1", 5000);
}
}

3.2 Server Programming

Establish a Socket Connection


To write a server application two sockets are needed.

 A ServerSocket which waits for the client requests (when a client makes a new
Socket())
 A plain old Socket socket to use for communication with the client.

Communication
getOutputStream() method is used to send the output through the socket.

Close the Connection


After finishing, it is important to close the connection by closing the socket as well as
input/output streams.

30
// A Java program for a Server
import java.net.*;
import java.io.*;

public class Server


{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");

System.out.println("Waiting for a client ...");

socket = server.accept();
System.out.println("Client accepted");

// takes input from the client socket


in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

31
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);

}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");

// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

32
Chapter 4: Result & Discussion

4.1 GUI OF PROJECT

FIG 4.1 GUI CHAT APPLICATION

33
4.2 CONNECTION BETWEEN CLIENT AND SERVER

FIG 4.2 RUNNING PROJECT VIEW

34
Chapter-5: Future Enhancement Conclusion And Limitation

5.1 Conclusion
This chapter has given a broad picture of the design of the software in terms of the
different modules used. It also gives us an idea about the degree to which each
module performs related tasks. We also get an idea about the interdependence among
the modules.

5.2 Limitations
There are mainly two limitations of the project and that are:
The firewall is to be disabled for intra network.
It is dependent on the specific algorithm used.

5.3 Future Enhancement Conclusion


There is always a room for improvements in any software package, however good and
efficient it may be done. But the most important thing should be flexible to accept
further modification. Right now we are just dealing with text communication. In future
this software may be extended to include features such as:

File transfer: this will enable the user to send files of different formats to others
via the chat application.

Voice chat: this will enhance the application to a higher level where
communication will be possible via voice calling as in telephone.

Video chat: this will further enhance the feature of calling into video
communication.

35
References

[1].Java Networking Concepts taught in class and text reference textbook by Herbert
Schildt from oracle press.
[2].Sockets in
https://docs.oracle.com/javase/tutorial/networking/sockets/definition.html
[3]. www.javatpoint.com
[4]. https://code.visualstudio.com/docs
[5]. https://www.tutorialspoint.com/sockets
[6]. https://www.journaldev.com/741/java-socket-programming-server-client

36

You might also like