Network Application

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

INTRODUCTION

Teleconferencing or Chatting, is a method of using technology to bring people and


ideas together despite of the geographical barriers.
The technology has been available for years but the acceptance it was quit recent.
Our project is an example of a chat server. It is made up of 2 applications the client
application, which runs on the users Pc and server application, which runs on any
Pc on the network.
To start chatting client should get connected to server where they can practice two
kinds of chatting, public one (message is broadcasted to all connected users) and
private one (between any 2 users only) and during the last one security measures
were taken.

Network Application

Network application exchange data between physically separated machines. For this to

occur the machines must be connected by a transmission media. There are many different types

of communication links and new ones continue to be developed. Coaxial cables, phone lines,

digital phone lines, fiber optic cable, satellite beam, and infrared waves are all used as

transmission media for exchange data between computers.

A network includes a group of computers connected by a physical link allowing data to be

exchanged between them. A local are network on LAN is a network of computers in close

physical proximity, usually a single building, but can be a group of adjacent buildings. Over the

last decades LANs have become an important component of the computer workplace.
Protocol Stacks

Very Early in the history of computer network development the concept of separating the

problem into multiple levels was adapted. With a multilevel architecture each layer can handle a

different aspect of networking and provide that functionality to the above layer. TCP/IP is a

specific implementation of a multi level network architecture. In both, the first and second

chapter, we are always repeating the same sentence, which is TCP/IP protocol. It is now the time

to dissect this sentence.

TCP

TCP (the Transmission Control Protocol ) has the responsibility for breaking up the message

into datagrams, reassembling them at the other end, resending anything that gets lost, and putting

things back in the right order. It may seem that TCP is doing all the work. And in small network it

is true. With TCP, there is no maximum message length. When a message is passed to the TCP

protocol, if it is too large to be sent in one peace, the message is broken up into chunks or packets

and sent one at a time to the destination address. The TCP packet contains the addressing

information. The TCP message also contains a packet number and total number of packets.

Because of the nature of the TCP/IP protocol, the packet may travel different paths and may arrive

in a different order than sent. TCP reassemble the packets in the proper order and requests the

retransmission of any missing or corrupted packets. TCP enables you to create and maintain a
connection to a remote computer. By using the connection, both computers can stream data

between each other.

IP

As the number of computers networked become larger, a system becomes necessary to

give remote computers the capability to recognize other remote computers; thus the IP addressing

method was born. Therefore, simply an IP address uniquely identifies any computer connected to

a network. This address is made up of 32 bits divided into 4 four bytes. But since the number of

connected computers is too large and since it is difficult to remember all their IP addresses, the

Domain Name Service (DNS) was designed. It has the job of transforming the unique computer

names (host name) into an IP address. Therefor, whenever in our project we run the client

application and enter the host name, this means that we are writing the IP address of the remote

computer we want to connect to indirectly. In general, TCP/IP is a set of protocols developed to

allow cooperating computers to share resources across the network.

Service Port

Till now, we have seen that TCP/IP forms the backbone for communication between

computers, but do you know how these computers speak to each other?

The answer is Ports. A port is a special location in the computers memory that exists when two

computers are communicating via TCP/IP. Application uses a port number to communicate and

the sending and receiving computers use this same port to exchange data. To make the job of
communication easier, some port numbers have been standardized, ex, (www Port 80, Ftp Port

20, 21, Etc). Our application uses a constant named IP-echoport = 7.

Sockets

The world is defining itself as a largely Intel-processor, windows-based set of desktops

communicating with back end servers of various types. Hardware and software technology

advances are pushing PCs into the role of every where communications devices. For software

applications to take advantage of increasingly sophisticated and feature-rich communications

technology, they require an Application Programming Interface (API) which provides a simple

and uniform access to this technology. WinSock has been this interface for TCP/IP on windows

systems for the last 3 years. It is now set to become the definitive applications interface for all
windows-based communication-capable applications.

Client-Server Application

When the program wishes to use TCP to exchange data, one of the programs should take

the role of a client while the other must take the role of a server. The client application initiates

what is called active open. It creates a socket and actively attempts to connect to server program.

On the other hand, the server application creates a socket and passively listens for incoming

connections from client, performing what is called passive open. When the client wants to

connect a server, it sends a connection request. The server is notified that some process is trying

to connect with it. By accepting the connection, the server completes what is called a virtual

circuit, a logical communication pathway between the two programs.


To review, there are five significant steps that a program that uses TCP must take to establish and

complete a connection.

The server side would follow these steps:


1. Create a socket
2. Listen for incoming connections from clients
3. Accept the client connection
4. Send and receive information

5. Close the socket when finished, terminating the conversation


6.
In case of the client, these steps are followed:

1. Create a socket
2. Specify the address and service port of the server program
3. Establish the connection with the server
4. Send and receive information

5. Close the socket when finished, terminating the conversation

GUI & JFRAME

The java swing package lets you make GUI components for your java applications and is
platform independent.

The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit.

You can use the Java GUI components like button , textbox etc from the library and do not have
to create the components from scratch.
The class JFrame is an extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture.

Container classes are classes that can have other components on it. So for creating a GUI, we
need at least one Container object Three types of containers

1. Panel : It is a pure container and is not a window in itself. The sole purpose of a Panel is
to organize the components on to a window.

2. Frame : It is a fully functioning window with its own title and icons.

3. Dialog : It can be thought of as a pop-up window that pops out when message has to be
displayed. It is not a fully functioning window like the Frame.

Diagrammatic Representation
LANGUAGE CODED
JAVA

JAVA SWING
IMPLEMENTATION & SOFTWARE USED:
NETBEANS IDE

GUI for display purpose

SOURCE CODE:

//In Main Package Chatboxserver


//com.socket

Database.java

package com.socket;

import java.io.*;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;
/**

*@Chetali

* @author Akash

*/

public class Database {

public String filePath;

public Database(String filePath){

this.filePath = filePath;

public boolean userExists(String username){

try{

File fXmlFile = new File(filePath);

DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("user");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;

if(getTagValue("username", eElement).equals(username)){

return true;

return false;

catch(Exception ex){

System.out.println("Database exception : userExists()");

return false;

public boolean checkLogin(String username, String password){

if(!userExists(username)){ return false; }

try{

File fXmlFile = new File(filePath);

DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();


Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("user");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

if(getTagValue("username", eElement).equals(username) &&


getTagValue("password", eElement).equals(password)){

return true;

System.out.println("Hippie");

return false;

catch(Exception ex){

System.out.println("Database exception : userExists()");

return false;

}
public void addUser(String username, String password){

try {

DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();

DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

Document doc = docBuilder.parse(filePath);

Node data = doc.getFirstChild();

Element newuser = doc.createElement("user");

Element newusername = doc.createElement("username");


newusername.setTextContent(username);

Element newpassword = doc.createElement("password");


newpassword.setTextContent(password);

newuser.appendChild(newusername);
newuser.appendChild(newpassword); data.appendChild(newuser);

TransformerFactory transformerFactory =
TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer();

DOMSource source = new DOMSource(doc);

StreamResult result = new StreamResult(new File(filePath));

transformer.transform(source, result);

catch(Exception ex){
System.out.println("Exceptionmodify xml");

public static String getTagValue(String sTag, Element eElement) {

NodeList nlList =
eElement.getElementsByTagName(sTag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();

Message.java
package com.socket;

import java.io.Serializable;

/**

*@Chetali

* @author Akash
*/

public class Message implements Serializable{

private static final long serialVersionUID = 1L;

public String type, sender, content, recipient;

public Message(String type, String sender, String content, String recipient){

this.type = type; this.sender = sender; this.content = content; this.recipient


= recipient;

@Override

public String toString(){

return "{type='"+type+"', sender='"+sender+"', content='"+content+"',


recipient='"+recipient+"'}";

SocketServer.java

package com.socket;

import java.io.*;

import java.net.*;
/**

*@Chetali

* @author Akash

*/

class ServerThread extends Thread {

public SocketServer server = null;

public Socket socket = null;

public int ID = -1;

public String username = "";

public ObjectInputStream streamIn = null;

public ObjectOutputStream streamOut = null;

public ServerFrame ui;

public ServerThread(SocketServer _server, Socket _socket){

super();

server = _server;

socket = _socket;
ID = socket.getPort();

ui = _server.ui;

public void send(Message msg){

try {

streamOut.writeObject(msg);

streamOut.flush();

catch (IOException ex) {

System.out.println("Exception [SocketClient : send(...)]");

public int getID(){

return ID;

@SuppressWarnings("deprecation")

public void run(){

ui.jTextArea1.append("\nServer Thread " + ID + " running.");

while (true){
try{

Message msg = (Message) streamIn.readObject();

server.handle(ID, msg);

catch(Exception ioe){

System.out.println(ID + " ERROR reading: " + ioe.getMessage());

server.remove(ID);

stop();

public void open() throws IOException {

streamOut = new ObjectOutputStream(socket.getOutputStream());

streamOut.flush();

streamIn = new ObjectInputStream(socket.getInputStream());

public void close() throws IOException {

if (socket != null) socket.close();

if (streamIn != null) streamIn.close();


if (streamOut != null) streamOut.close();

public class SocketServer implements Runnable {

public ServerThread clients[];

public ServerSocket server = null;

public Thread thread = null;

public int clientCount = 0, port = 13000;

public ServerFrame ui;

public Database db;

public SocketServer(ServerFrame frame){

clients = new ServerThread[50];

ui = frame;

db = new Database(ui.filePath);

try{

server = new ServerSocket(port);

port = server.getLocalPort();

ui.jTextArea1.append("Server startet. IP : " +


InetAddress.getLocalHost() + ", Port : " + server.getLocalPort());

start();

}
catch(IOException ioe){

ui.jTextArea1.append("Can not bind to port : " + port + "\nRetrying");

ui.RetryStart(0);

public SocketServer(ServerFrame frame, int Port){

clients = new ServerThread[50];

ui = frame;

port = Port;

db = new Database(ui.filePath);

try{

server = new ServerSocket(port);

port = server.getLocalPort();

ui.jTextArea1.append("Server startet. IP : " +


InetAddress.getLocalHost() + ", Port : " + server.getLocalPort());

start();

catch(IOException ioe){

ui.jTextArea1.append("\nCan not bind to port " + port + ": " +


ioe.getMessage());

}
}

public void run(){

while (thread != null){

try{

ui.jTextArea1.append("\nWaiting for a client ...");

addThread(server.accept());

catch(Exception ioe){

ui.jTextArea1.append("\nServer accept error: \n");

ui.RetryStart(0);

public void start(){

if (thread == null){

thread = new Thread(this);

thread.start();

@SuppressWarnings("deprecation")
public void stop(){

if (thread != null){

thread.stop();

thread = null;

private int findClient(int ID){

for (int i = 0; i < clientCount; i++){

if (clients[i].getID() == ID){

return i;

return -1;

public synchronized void handle(int ID, Message msg){

if (msg.content.equals(".bye")){

Announce("signout", "SERVER", msg.sender);

remove(ID);

else{
if(msg.type.equals("login")){

if(findUserThread(msg.sender) == null){

if(db.checkLogin(msg.sender, msg.content)){

clients[findClient(ID)].username = msg.sender;

clients[findClient(ID)].send(new Message("login", "SERVER",


"TRUE", msg.sender));

Announce("newuser", "SERVER", msg.sender);

SendUserList(msg.sender);

else{

clients[findClient(ID)].send(new Message("login", "SERVER",


"FALSE", msg.sender));

else{

clients[findClient(ID)].send(new Message("login", "SERVER",


"FALSE", msg.sender));

else if(msg.type.equals("message")){

if(msg.recipient.equals("All")){

Announce("message", msg.sender, msg.content);


}

else{

findUserThread(msg.recipient).send(new Message(msg.type,
msg.sender, msg.content, msg.recipient));

clients[findClient(ID)].send(new Message(msg.type, msg.sender,


msg.content, msg.recipient));

else if(msg.type.equals("test")){

clients[findClient(ID)].send(new Message("test", "SERVER", "OK",


msg.sender));

else if(msg.type.equals("signup")){

if(findUserThread(msg.sender) == null){

if(!db.userExists(msg.sender)){

db.addUser(msg.sender, msg.content);

clients[findClient(ID)].username = msg.sender;

clients[findClient(ID)].send(new Message("signup",
"SERVER", "TRUE", msg.sender));

clients[findClient(ID)].send(new Message("login", "SERVER",


"TRUE", msg.sender));

Announce("newuser", "SERVER", msg.sender);


SendUserList(msg.sender);

else{

clients[findClient(ID)].send(new Message("signup",
"SERVER", "FALSE", msg.sender));

else{

clients[findClient(ID)].send(new Message("signup", "SERVER",


"FALSE", msg.sender));

else if(msg.type.equals("upload_req")){

if(msg.recipient.equals("All")){

clients[findClient(ID)].send(new Message("message", "SERVER",


"Uploading to 'All' forbidden", msg.sender));

else{

findUserThread(msg.recipient).send(new Message("upload_req",
msg.sender, msg.content, msg.recipient));

}
else if(msg.type.equals("upload_res")){

if(!msg.content.equals("NO")){

String IP =
findUserThread(msg.sender).socket.getInetAddress().getHostAddress();

findUserThread(msg.recipient).send(new Message("upload_res",
IP, msg.content, msg.recipient));

else{

findUserThread(msg.recipient).send(new Message("upload_res",
msg.sender, msg.content, msg.recipient));

} }

public void Announce(String type, String sender, String content){

Message msg = new Message(type, sender, content, "All");

for(int i = 0; i < clientCount; i++){

clients[i].send(msg);

public void SendUserList(String toWhom){

for(int i = 0; i < clientCount; i++){


findUserThread(toWhom).send(new Message("newuser", "SERVER",
clients[i].username, toWhom));

public ServerThread findUserThread(String usr){

for(int i = 0; i < clientCount; i++){

if(clients[i].username.equals(usr)){

return clients[i];

return null;

@SuppressWarnings("deprecation")

public synchronized void remove(int ID){

int pos = findClient(ID);

if (pos >= 0){

ServerThread toTerminate = clients[pos];

ui.jTextArea1.append("\nRemoving client thread " + ID + " at " + pos);

if (pos < clientCount-1){

for (int i = pos+1; i < clientCount; i++){

clients[i-1] = clients[i];
}

clientCount--;

try{

toTerminate.close();

catch(IOException ioe){

ui.jTextArea1.append("\nError closing thread: " + ioe);

toTerminate.stop();

private void addThread(Socket socket){

if (clientCount < clients.length){

ui.jTextArea1.append("\nClient accepted: " + socket);

clients[clientCount] = new ServerThread(this, socket);

try{

clients[clientCount].open();

clients[clientCount].start();

clientCount++;
}

catch(IOException ioe){

ui.jTextArea1.append("\nError opening thread: " + ioe);

else{

ui.jTextArea1.append("\nClient refused: maximum " + clients.length +


" reached.");

ServerFrame.java
package com.socket;

import java.awt.Color;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.io.File;

import javax.swing.JFileChooser;

import javax.swing.UIManager;

/**
*@Chetali

* @author Akash

*/

public class ServerFrame extends javax.swing.JFrame {

public SocketServer server;

public Thread serverThread;

public String filePath = "D:/Data.xml";

public JFileChooser fileChooser;

public ServerFrame() {

initComponents();

jTextField3.setEditable(false);

jTextField3.setBackground(Color.WHITE);

fileChooser = new JFileChooser();

jTextArea1.setEditable(false); }

public boolean isWin32(){

return System.getProperty("os.name").startsWith("Windows"); }

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

Startserverr = new javax.swing.JButton();


jScrollPane1 = new javax.swing.JScrollPane();

jTextArea1 = new javax.swing.JTextArea();

jLabel3 = new javax.swing.JLabel();

jTextField3 = new javax.swing.JTextField();

Browsee = new javax.swing.JButton();

jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("Server Box");

Startserverr.setText("Start Server");

Startserverr.setEnabled(false);

Startserverr.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

StartserverrActionPerformed(evt); }

jTextArea1.setColumns(20);

jTextArea1.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N

jTextArea1.setRows(5);

jScrollPane1.setViewportView(jTextArea1);

jLabel3.setText("Database File : ");

Browsee.setText("Browse...");

Browsee.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {

BrowseeActionPerformed(evt);

});

jLabel1.setText(" A.P.");

javax.swing.GroupLayout layout = new


javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.Gro
upLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)

.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()

.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jTextField3,
javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(Browsee,
javax.swing.GroupLayout.PREFERRED_SIZE, 91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(Startserverr)))

.addContainerGap())

.addGroup(layout.createSequentialGroup()

.addGap(263, 263, 263)

.addComponent(jLabel1)

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))

);

layout.setVerticalGroup( layout.createParallelGroup(javax.swing.Group
Layout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)

.addComponent(jTextField3,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel3)

.addComponent(Browsee)

.addComponent(Startserverr))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jLabel1))

);

pack();

}// </editor-fold>

private void StartserverrActionPerformed(java.awt.event.ActionEvent evt) {

server = new SocketServer(this);

Startserverr.setEnabled(false); Browsee.setEnabled(false);

public void RetryStart(int port){

if(server != null){ server.stop(); }

server = new SocketServer(this, port);

private void BrowseeActionPerformed(java.awt.event.ActionEvent evt) {

fileChooser.showDialog(this, "Select");

File file = fileChooser.getSelectedFile();

if(file != null){

filePath = file.getPath();

if(this.isWin32()){ filePath = filePath.replace("\\", "/"); }


jTextField3.setText(filePath);

Startserverr.setEnabled(true);

public static void main(String args[]) {

try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelCl
assName());

catch(Exception ex){

System.out.println("Look & Feel Exception");

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new ServerFrame().setVisible(true);

});

// Variables declaration - do not modify

private javax.swing.JButton Browsee;

private javax.swing.JButton Startserverr;


private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel3;

private javax.swing.JScrollPane jScrollPane1;

public javax.swing.JTextArea jTextArea1;

private javax.swing.JTextField jTextField3;

// End of variables declaration

//In Main Package Chatbox


//com.socket

Message.java

package com.socket;

import java.io.Serializable;

/**

*@Chetali
* @author Akash

*/

public class Message implements Serializable{

private static final long serialVersionUID = 1L;

public String type, sender, content, recipient;

public Message(String type, String sender, String content, String recipient){

this.type = type; this.sender = sender; this.content = content; this.recipient


= recipient;

@Override

public String toString(){

return "{type='"+type+"', sender='"+sender+"', content='"+content+"',


recipient='"+recipient+"'}";

SocketClient.java

package com.socket;

import com.ui.ChatFrame;

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

import java.util.Date;

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;

/**

*@Chetali

* @author Akash

*/

public class SocketClient implements Runnable{

public int port;

public String serverAddr;

public Socket socket;

public ChatFrame ui;

public ObjectInputStream In;

public ObjectOutputStream Out;

public SocketClient(ChatFrame frame) throws IOException{

ui = frame; this.serverAddr = ui.serverAddr; this.port = ui.port;


socket = new Socket(InetAddress.getByName(serverAddr), port);

Out = new ObjectOutputStream(socket.getOutputStream());

Out.flush();

In = new ObjectInputStream(socket.getInputStream());

@Override

public void run() {

boolean keepRunning = true;

while(keepRunning){

try {

Message msg = (Message) In.readObject();

System.out.println("Incoming : "+msg.toString());

if(msg.type.equals("message")){

if(msg.recipient.equals(ui.username)){

ui.mesgarea.append("["+msg.sender +" > Me] : " + msg.content


+ "\n");

else{

ui.mesgarea.append("["+ msg.sender +" > "+ msg.recipient


+"] : " + msg.content + "\n");

}
if(!msg.content.equals(".bye") && !
msg.sender.equals(ui.username)){

String msgTime = (new Date()).toString();

else if(msg.type.equals("login")){

if(msg.content.equals("TRUE")){

ui.loginn.setEnabled(false); ui.signupp.setEnabled(false);

ui.mesgsend.setEnabled(true);

ui.mesgarea.append("[SERVER > Me] : Login Successful\n");

ui.Akashh.setEnabled(false); ui.passwordd.setEnabled(false);
}

else{

ui.mesgarea.append("[SERVER > Me] : Login Failed\n");

else if(msg.type.equals("test")){

ui.connectt.setEnabled(false);

ui.loginn.setEnabled(true); ui.signupp.setEnabled(true);

ui.Akashh.setEnabled(true); ui.passwordd.setEnabled(true);

ui.localhostt.setEditable(false); ui.localhost2.setEditable(false);
}

else if(msg.type.equals("newuser")){

if(!msg.content.equals(ui.username)){

boolean exists = false;

for(int i = 0; i < ui.model.getSize(); i++){

if(ui.model.getElementAt(i).equals(msg.content)){

exists = true; break;

if(!exists){ ui.model.addElement(msg.content); }

else if(msg.type.equals("signup")){

if(msg.content.equals("TRUE")){

ui.loginn.setEnabled(false); ui.signupp.setEnabled(false);

ui.mesgarea.append("[SERVER > Me] : Singup Successful\n");

else{

ui.mesgarea.append("[SERVER > Me] : Signup Failed\n");

}
}

else if(msg.type.equals("signout")){

if(msg.content.equals(ui.username)){

ui.mesgarea.append("["+ msg.sender +" > Me] : Bye\n");

ui.connectt.setEnabled(true); ui.mesgsend.setEnabled(false);

ui.localhostt.setEditable(true); ui.localhost2.setEditable(true);

for(int i = 1; i < ui.model.size(); i++){

ui.model.removeElementAt(i);

ui.clientThread.stop();

else{

ui.model.removeElement(msg.content);

ui.mesgarea.append("["+ msg.sender +" > All] : "+ msg.content


+" has signed out\n");

else if(msg.type.equals("upload_req"))

{
if(JOptionPane.showConfirmDialog(ui, ("Accept
'"+msg.content+"' from "+msg.sender+" ?")) == 0)

JFileChooser jf = new JFileChooser();

jf.setSelectedFile(new File(msg.content));

int returnVal = jf.showSaveDialog(ui);

String saveTo = jf.getSelectedFile().getPath();

else{

send(new Message("upload_res", ui.username, "NO",


msg.sender));

else if(msg.type.equals("upload_res")){

if(!msg.content.equals("NO")){

int port = Integer.parseInt(msg.content);

String addr = msg.sender;

else{

ui.mesgarea.append("[SERVER > Me] : "+msg.sender+"


rejected file request\n");

}
}

else{

ui.mesgarea.append("[SERVER > Me] : Unknown message


type\n");

catch(Exception ex) {

keepRunning = false;

ui.mesgarea.append("[Application > Me] : Connection Failure\n");

ui.connectt.setEnabled(true);

ui.localhostt.setEditable(true);

ui.localhost2.setEditable(true);

for(int i = 1; i < ui.model.size(); i++)

ui.model.removeElementAt(i);

ui.clientThread.stop();

System.out.println("Exception SocketClient run()");

ex.printStackTrace();

}
}

public void send(Message msg){

try {

Out.writeObject(msg);

Out.flush();

System.out.println("Outgoing : "+msg.toString());

if(msg.type.equals("message") && !msg.content.equals(".bye"))

String msgTime = (new Date()).toString();

catch (IOException ex) {

System.out.println("Exception SocketClient send()");

public void closeThread(Thread t){

t = null;

}
//com.socket
ChatFrame.java

package com.ui;

import com.socket.Message;

import com.socket.SocketClient;

import java.awt.event.WindowEvent;

import java.awt.event.WindowListener;

import java.io.File;

import javax.swing.DefaultListModel;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.UIManager;

import oracle.jrockit.jfr.JFR;
/**

*@Chetali

* @author Akash

*/

public class ChatFrame extends javax.swing.JFrame {

public SocketClient client;

public int port;

public String serverAddr, username, password;

public Thread clientThread;

public DefaultListModel model;

public File file;

public String historyFile = "D:/History.xml";

public ChatFrame() {

initComponents();

this.setTitle("Chat Box");

model.addElement("All");

jList1.setSelectedIndex(0);

this.addWindowListener(new WindowListener() {
@Override public void windowOpened(WindowEvent e) {}

@Override public void windowClosing(WindowEvent e)


{ try{ client.send(new Message("message", username, ".bye", "SERVER"));
clientThread.stop(); }catch(Exception ex){} }

@Override public void windowClosed(WindowEvent e) {}

@Override public void windowIconified(WindowEvent e) {}

@Override public void windowDeiconified(WindowEvent e) {}

@Override public void windowActivated(WindowEvent e) {}

@Override public void windowDeactivated(WindowEvent e) {}

});

public boolean isWin32(){

return System.getProperty("os.name").startsWith("Windows");

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

localhostt = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();

localhost2 = new javax.swing.JTextField();


connectt = new javax.swing.JButton();

Akashh = new javax.swing.JTextField();

jLabel3 = new javax.swing.JLabel();

jLabel4 = new javax.swing.JLabel();

signupp = new javax.swing.JButton();

passwordd = new javax.swing.JPasswordField();

jSeparator1 = new javax.swing.JSeparator();

jScrollPane1 = new javax.swing.JScrollPane();

mesgarea = new javax.swing.JTextArea();

jScrollPane2 = new javax.swing.JScrollPane();

jList1 = new javax.swing.JList();

jLabel5 = new javax.swing.JLabel();

mesgtext = new javax.swing.JTextField();

mesgsend = new javax.swing.JButton();

loginn = new javax.swing.JButton();

jLabel6 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Host Address : ");

localhostt.setText("localhost");

jLabel2.setText("Host Port : ");


localhost2.setText("13000");

localhost2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

localhost2ActionPerformed(evt);

});

connectt.setText("Connect");

connectt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

connecttActionPerformed(evt);

});

Akashh.setText("Akash");

Akashh.setEnabled(false);

Akashh.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

AkashhActionPerformed(evt);

});

jLabel3.setText("Password :");
jLabel4.setText("Username :");

signupp.setText("SignUp");

signupp.setEnabled(false);

signupp.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

signuppActionPerformed(evt);

});

passwordd.setText("chetali");

passwordd.setEnabled(false);

passwordd.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

passworddActionPerformed(evt);

});

mesgarea.setColumns(20);

mesgarea.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N

mesgarea.setRows(5);

jScrollPane1.setViewportView(mesgarea);

jList1.setModel((model = new DefaultListModel()));


jScrollPane2.setViewportView(jList1);

jLabel5.setText("Message : ");

mesgsend.setText("Send Message ");

mesgsend.setEnabled(false);

mesgsend.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

mesgsendActionPerformed(evt);

});

loginn.setText("Login");

loginn.setEnabled(false);

loginn.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

loginnActionPerformed(evt);

});

jLabel6.setText(" A.P.");

javax.swing.GroupLayout layout = new


javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);
layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.Gr
oupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)

.addComponent(jSeparator1,
javax.swing.GroupLayout.Alignment.TRAILING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
TRAILING)

.addComponent(jLabel1)

.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)

.addComponent(Akashh)

.addComponent(localhostt,
javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE))

.addGap(18, 18, 18)

.
addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.T
RAILING)

.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELAT
ED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)

.addComponent(localhost2)

.addComponent(passwordd,
javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING, false)

.addComponent(connectt,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()

.addComponent(loginn, javax.swing.GroupLayout.PREFERRED_SIZE,
70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(signupp,
javax.swing.GroupLayout.PREFERRED_SIZE, 81,
javax.swing.GroupLayout.PREFERRED_SIZE))))

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()

.addComponent(jScrollPane1)

.addGap(18, 18, 18)


.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 108,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()

.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(mesgtext)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELAT
ED)

.addComponent(mesgsend)

.addGap(8, 8, 8)))

.addContainerGap())

.addGroup(layout.createSequentialGroup()

.addGap(249, 249, 249)

.addComponent(jLabel6)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)

.addComponent(jLabel1)

.addComponent(localhostt,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel2)

.addComponent(localhost2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(connectt))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELAT
ED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)

.addComponent(Akashh,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel3)

.addComponent(jLabel4)

.addComponent(signupp)

.addComponent(passwordd,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(loginn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELAT
ED)

.addComponent(jSeparator1,
javax.swing.GroupLayout.PREFERRED_SIZE, 10,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)

.addComponent(jScrollPane1)

.addComponent(jScrollPane2,
javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))

.addGap(19, 19, 19)


.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)

.addComponent(mesgtext,
javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel5)

.addComponent(mesgsend,
javax.swing.GroupLayout.PREFERRED_SIZE, 39,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addComponent(jLabel6)
.addContainerGap())

);

pack();

}// </editor-fold>

private void connecttActionPerformed(java.awt.event.ActionEvent evt) {

serverAddr = localhostt.getText(); port =


Integer.parseInt(localhost2.getText());

if(!serverAddr.isEmpty() && !localhost2.getText().isEmpty()){

try{

client = new SocketClient(this);

clientThread = new Thread(client);

clientThread.start();

client.send(new Message("test", "testUser", "testContent",


"SERVER"));

catch(Exception ex){

mesgarea.append("[Application > Me] : Server not found\n");

} } }

private void loginnActionPerformed(java.awt.event.ActionEvent evt) {

username = Akashh.getText();
password = passwordd.getText();

if(!username.isEmpty() && !password.isEmpty()){

client.send(new Message("login", username, password, "SERVER"));

private void mesgsendActionPerformed(java.awt.event.ActionEvent evt) {

String msg = mesgtext.getText();

String target = jList1.getSelectedValue().toString();

if(!msg.isEmpty() && !target.isEmpty()){

mesgtext.setText("");

client.send(new Message("message", username, msg, target));

} }

private void signuppActionPerformed(java.awt.event.ActionEvent evt) {

username = Akashh.getText();

password = passwordd.getText();

if(!username.isEmpty() && !password.isEmpty()){

client.send(new Message("signup", username, password, "SERVER"));

private void AkashhActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here: }

private void passworddActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here: }

private void localhost2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here: }

public static void main(String args[]) {

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

catch(Exception ex){

System.out.println("Look & Feel exception");

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new ChatFrame().setVisible(true);

});

// Variables declaration - do not modify

public javax.swing.JTextField Akashh;

public javax.swing.JButton connectt;


private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JLabel jLabel6;

public javax.swing.JList jList1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JSeparator jSeparator1;

public javax.swing.JTextField localhost2;

public javax.swing.JTextField localhostt;

public javax.swing.JButton loginn;

public javax.swing.JTextArea mesgarea;

public javax.swing.JButton mesgsend;

public javax.swing.JTextField mesgtext;

public javax.swing.JPasswordField passwordd;

public javax.swing.JButton signupp;

// End of variables declaration

}
SCREENSHOTS:
ChatFrame.java (jFrame)

ServerFrame.java (jFrame)
All Chat Boxes at start up

After selecting Data.xml file


After Connecting 1st Client by entering Username & Password

After Connecting All the Clients by entering Username & Password


Sending Message to All User

Sending Message to Selected User


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.

You might also like