java mp
java mp
Microproject
On
“Chat Application”
Submitted By:
CERTIFICATE
ACKNOWLEDGEMENT
ABSTRACT
The Chat Application project in Java is an endeavor to develop a robust and user-
friendly messaging platform facilitating real-time communication among users.
Utilizing Java programming language along with various libraries and frameworks,
the project aims to create a scalable and efficient chat application capable of
handling multiple users simultaneously.
Key features include user authentication, enabling secure registration and login,
real-time messaging functionality allowing instant exchange of text-based
messages, support for group chat facilitating communication among multiple
participants, and file sharing capability for exchanging images, documents, and
multimedia content within individual or group chats. Additionally, the application
offers emoticons and stickers for expressing emotions, message encryption to
ensure privacy and security, offline messaging for sending messages to users who
are currently offline, and user profiles containing personalized information for
effective online presence management.
INDEX
1. Introduction 06
2. Components 06
3. Architecture 07
4. Socket Programming 07
6. Security Considerations 09
7. Code 10-20
8. Output 21
7. Conclusion 25
8. References 25
MICROPROJECT JAVA PROGRAMMING 2
INTRODUCTION
In today's digital era, communication has become an integral part of our daily lives,
with messaging platforms serving as primary means of interaction. The Chat
Application project in Java endeavors to address the growing need for efficient and
user-friendly messaging solutions. With the widespread adoption of Java
programming language and its robust ecosystem of libraries and frameworks,
developing a chat application in Java offers numerous advantages, including cross-
platform compatibility, scalability, and security. This project aims to leverage these
strengths to create a comprehensive messaging platform capable of meeting the
diverse communication needs of users.
The Chat Application project seeks to provide a seamless and intuitive interface for
real-time communication, enabling users to exchange messages, share files, and
engage in group discussions effortlessly. By incorporating features such as user
authentication, message encryption, and offline messaging, the application
prioritizes security, and reliability. Furthermore, customization options allow users
to personalize their chat experience according to their preferences, enhancing user
engagement and satisfaction.
ARCHITECTURE
1
❖ Client and Server model
A client and server networking model is a model in which computers such as
servers provide the network services to the other computers such as clients to
perform a user based tasks. This model is known as client-server networking
model.
A client-server chat application typically involves clients (user interfaces)
communicating with a central server. Clients send messages to the server,
which then relays them to the intended recipients. It often uses a protocol like
TCP/IP for reliable data transfer. The server manages user connections, stores
chat history, and facilitates message distribution.
COMPONENTS
CLIENT
1. A client is a program that runs on the local machine requesting service from the
server. A client program is a finite program means that the service started by
the user and terminates when the service is completed.
2. Clients typically communicate with servers by using the TCP/IP protocol suite.
TCP is a connection-oriented protocol, which means the protocol establishes
and maintains connections until the application programs at each end have
finished exchanging messages.
SERVER
1. A server is a program that runs on the remote machine providing services to the
clients. When the client requests for a service, then the server opens the door
for the incoming requests, but it never initiates the service.
2. A server program is an infinite program means that when it starts, it runs
infinitely unless the problem arises. The server waits for the incoming requests
from the clients. When the request arrives at the server, then it responds to the
request.
2
MICROPROJECT JAVA PROGRAMMING 2
THEORETICAL BACKGROUND
The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process
events.
➢ KeyListener Interface
The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent. The KeyListener interface is found in
java.awt.event package, and it has three methods.
3
MICROPROJECT JAVA PROGRAMMING 2
➢ JFRAME
➢ Swing
• JLabel
4
MICROPROJECT JAVA PROGRAMMING 2
• JTextField
• JButton
• JTable
SOCKET PROGRAMMING
5
MICROPROJECT JAVA PROGRAMMING 2
Client server model is the standard model which has been accepted by many
for developing security network applications. In this model, there is a notion of
client and notion of server.
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. Sockets are the
endpoints of logical connections between two hosts and can be used to send
and receive data. It 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.
6
MICROPROJECT JAVA PROGRAMMING 2
Client Execution: A client firstly must have to register itself by sending username
to the server and then any of two registered clients can communicate with each
other.
SECURITY CONSIDERATIONS:
➢ Code:
7
MICROPROJECT JAVA PROGRAMMING 2
Client.java
import java.net.Socket;
import java.util.Random;
import java.io.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
static Client c;
private static int key = 0;
BufferedReader br;
PrintWriter out;
Socket socket;
// Declare components
private JLabel heading=new JLabel("Client Area");
private JTextArea msgArea=new JTextArea();
private JTextField msgInput=new JTextField();
private Font font=new Font("Roboto",Font.PLAIN,20);
public Client()
{
try
{
decor('>');
System.out.println("Sending request to server..");
socket = new Socket("127.0.0.1",7777);
System.out.println("Connection done!");
decor('<');
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
sendKey();
createGUI();
handleEvents();
startReading();
startWriting();
}catch(Exception e)
{
8
MICROPROJECT JAVA PROGRAMMING 2
heading.setIcon(ii);
heading.setHorizontalTextPosition(SwingConstants.CENTER);
heading.setVerticalTextPosition(SwingConstants.BOTTOM);
heading.setHorizontalAlignment(SwingConstants.CENTER);
heading.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
msgArea.setEditable(false);
msgInput.setHorizontalAlignment(SwingConstants.CENTER);
}
private void handleEvents()
{
msgInput.addKeyListener(new KeyListener() {
9
MICROPROJECT JAVA PROGRAMMING 2
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
// System.out.println("key released :"+e.getKeyCode());
if(e.getKeyCode()==10)
{
System.out.println("You have pressed enter button");
String contentToSend=msgInput.getText();
String encryptedContent = encrypt(contentToSend, key);
msgArea.append("\nMe : "+contentToSend+"\n");
out.println(encryptedContent);
out.flush();
msgInput.setText("");
msgInput.requestFocus();
}
}
});
}
10
MICROPROJECT JAVA PROGRAMMING 2
if (Character.isLetter(ch)) {
char base = Character.isLowerCase(ch) ? 'a' : 'A';
char encryptedChar = (char) (base + (ch - base + shift) % 26); //65+(72-
65+2)%26
encryptedMessage.append(encryptedChar);
} else {
encryptedMessage.append(ch); // Keep non-alphabetic characters
unchanged
}
}
return encryptedMessage.toString();
}
// Function to decrypt an encrypted message using a shift cipher
public static String decrypt(String encryptedMessage, int shift) {
return encrypt(encryptedMessage, 26 - shift); // Decrypting is the same as
encrypting with the opposite shift
}
public void startReading()
{
// For reading from server
Runnable r1 = ()->
{
System.out.println("Reader started..");
try
{
while(!socket.isClosed()){
decor('-');
11
MICROPROJECT JAVA PROGRAMMING 2
decor('-');
// if(decryptedMsg.equals("bye") || decryptedMsg.equals(null))
if(decryptedMsg.equals("bye"))
{
TerminateConnection();
return;
}
}
}
catch(Exception e)
{
};
new Thread(r1).start();
}
12
MICROPROJECT JAVA PROGRAMMING 2
catch(Exception e)
{
};
new Thread(r2).start();
}
public void decor(char ch)
{
System.out.println();
for(int i=0;i<=40;i++)
{
System.out.print(ch);
}
System.out.println();
}
public void TerminateConnection()
{
try {
socket.close();
JOptionPane.showMessageDialog(this, "Server terminated the chat");
msgInput.setEditable(false);
c.dispose();
// System.out.println("Connection Terminated!");
System.exit(0);
} catch (Exception e) {
}
}
public static void main(String args[])
{
System.out.println("Client Here!");
c=new Client();
}
}
Server.java
import java.net.*;
import java.io.*;
import java.util.Random;
import java.awt.*;
13
MICROPROJECT JAVA PROGRAMMING 2
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public Server() {
try {
server = new ServerSocket(7777);
decor('>');
System.out.println("Server is ready to accept the connection");
System.out.println("Waiting...");
decor('<');
socket = server.accept();
// For Reading from socket
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// For Writing to socket
out = new PrintWriter(socket.getOutputStream());
acceptKey();
createGUI();
handleEvents();
startReading();
startWriting();
} catch (Exception e) {
e.printStackTrace();
}
}
public void acceptKey()
{
try {
decor('~');
System.out.println("Waiting for key...");
key = Integer.parseInt(br.readLine());
14
MICROPROJECT JAVA PROGRAMMING 2
System.out.println("Recieved Key:"+key);
decor('~');
} catch (Exception e) {
e.printStackTrace();
}
}
private void createGUI()
{
// gui code
this.setTitle("Server Messager[END]");
this.setSize(600,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
// coding for component
heading.setFont(font);
msgArea.setFont(font);
msgInput.setFont(font);
ImageIcon ii=new ImageIcon("app_logo.jpeg");
Image img=ii.getImage();
Image newimg=img.getScaledInstance(90,90,Image.SCALE_SMOOTH);
ii=new ImageIcon(newimg);
heading.setIcon(ii);
heading.setHorizontalTextPosition(SwingConstants.CENTER);
heading.setVerticalTextPosition(SwingConstants.BOTTOM);
heading.setHorizontalAlignment(SwingConstants.CENTER);
heading.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
msgArea.setEditable(false);
msgInput.setHorizontalAlignment(SwingConstants.CENTER);
15
MICROPROJECT JAVA PROGRAMMING 2
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
// System.out.println("key released :"+e.getKeyCode());
if(e.getKeyCode()==10)
{
System.out.println("You have pressed enter button");
String contentToSend=msgInput.getText();
String encryptedContent = encrypt(contentToSend, key);
msgArea.append("\nMe : "+contentToSend+"\n");
out.println(encryptedContent);
out.flush();
msgInput.setText("");
msgInput.requestFocus();
}
}
});
}
//Function to encrypt message
public static String encrypt(String message, int shift) {
StringBuilder encryptedMessage = new StringBuilder();
if (Character.isLetter(ch)) {
char base = Character.isLowerCase(ch) ? 'a' : 'A';
char encryptedChar = (char) (base + (ch - base + shift) % 26); //65+(72-
65+2)%26
encryptedMessage.append(encryptedChar);
} else {
encryptedMessage.append(ch); // Keep non-alphabetic characters
unchanged
16
MICROPROJECT JAVA PROGRAMMING 2
}
}
return encryptedMessage.toString();
}
// Function to decrypt an encrypted message using a shift cipher
public static String decrypt(String encryptedMessage, int shift) {
return encrypt(encryptedMessage, 26 - shift); // Decrypting is the same as
encrypting with the opposite shift
}
public void startReading() {
// For reading from client
Runnable r1 = () -> {
System.out.println("Reader started..");
try {
while (!socket.isClosed()) {
decor('-');
String msg = br.readLine();
System.out.println("Recieved Message from client:"+msg);
String decryptedMsg = decrypt(msg, key);
msgArea.append("\nRecieved Message from client:"+msg);
// System.out.println("Decrypted Message from
client:"+decryptedMsg);
if(decryptedMsg.equals("bye") )
{
TerminateConnection();
return;
}
msgArea.append("\nDecrypted msg from Client :"+decryptedMsg);
// System.out.println("Client: "+decryptedMsg);
decor('-');
}
} catch (Exception e) { }
};
new Thread(r1).start();
}
17
MICROPROJECT JAVA PROGRAMMING 2
if(content.equals("bye"))
{
TerminateConnection();
break;
}
out.flush();
}
} catch (Exception e) {
};
new Thread(r2).start();
}
public void TerminateConnection()
{
try {
socket.close();
System.out.println("Connection Terminated!");
System.exit(0);
} catch (Exception e) {
}
}
public void decor(char ch)
{
System.out.println();
for(int i=0;i<=40;i++)
{
System.out.print(ch);
}
System.out.println();
}
public static void main(String[] args) {
System.out.println("Server Open...");
18
MICROPROJECT JAVA PROGRAMMING 2
s=new Server();
}
}
➢ Output:
CO3: Develop client/server applications using TCP/IP and UDP socket programming.
19
MICROPROJECT JAVA PROGRAMMING 2
CONCLUSION:
The Chat Application project in Java represents a significant advancement in the realm
of digital communication, offering a feature-rich and user-friendly platform for real-time
messaging. By leveraging the capabilities of Java programming language and modern
technologies, this project has successfully developed a scalable, secure, and cross-
platform solution capable of meeting the diverse communication needs of users. With
its intuitive interface, robust features, and emphasis on privacy and security, the Chat
Application aims to enhance collaboration, foster connectivity, and streamline
communication processes in various contexts.
REFERENCES:
https://www.baeldung.com/
https://www.geeksforgeeks.org/java/
https://en.wikipedia.org/wiki/Swing_(Java)
https://en.wikipedia.org/wiki/JavaFX
20