0% found this document useful (0 votes)
339 views40 pages

Java-Based Distributed Chat Server

This document summarizes a distributed computing project that created an online chatting room application for sharing images and chatting using Java. The application uses a client-server model where a central server manages connections between multiple clients. The clients can chat, view conversations, and share images by sending them to the server which then broadcasts them to other clients. Java's BufferedImage class was used to handle image data transfer between clients via the server using sockets. The project aims to demonstrate uses of distributed computing in file sharing and was implemented using Java and the Eclipse IDE.

Uploaded by

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

Java-Based Distributed Chat Server

This document summarizes a distributed computing project that created an online chatting room application for sharing images and chatting using Java. The application uses a client-server model where a central server manages connections between multiple clients. The clients can chat, view conversations, and share images by sending them to the server which then broadcasts them to other clients. Java's BufferedImage class was used to handle image data transfer between clients via the server using sockets. The project aims to demonstrate uses of distributed computing in file sharing and was implemented using Java and the Eclipse IDE.

Uploaded by

anis
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DISTRIBUTED COMPUTING

PROJECT REPORT

DISTRIBUTED COMPUTING IN
TRANSFERRING IMAGE USING JAVA LANGUAGE

NAME
ANIS NUR HAMIZAH BINTI KAMARUDIN
RAJA NURUL IZZATI BINTI RAJA HANAFIAH

1.0 INTRODUCTION
0

ID NUMBER
17173
17236

Sharing files using devices became essential nowadays. To show the contribution of
Distributed Computing in this application, we decided to create an online chatting room for
sharing images and chatting. It is based on Client-Server application using java. A server will be
established for the connection between the client and servers. Client/server architecture is a
computing model in which the server hosts, delivers and manages most of the resources and
services to be consumed by the client. This type of architecture has one or more client computers
connected to a central server over a network or Internet connection. This system shares
computing resources.

2.0 OBJECTIVE
This project is aimed to establish a connection between Client and Server to allow the
user to chat and share images among them.

3.0 PROJECT OVERVIEW


This project is to show the uses of Distributed Computing in our daily life. As example
we would like to create an application to allow the user chatting and share images between them.
The conversation will be join by many Clients from different desktop and a server like a
broadcast message. They can view the conversation in the window and sending each other
messages. The connection is established using the LAN network and Internet
Client/server architecture may also be referred to as a networking computing model
because all the requests and services are delivered over a network. Client/server architecture is a
producer-consumer computing architecture where the server acts as the producer and the client as
a consumer. The server houses and provides high-end, computing-intensive services to the client
on demand. These services can include applications access, storage, file sharing, printer access
and/or direct access to the servers raw computing power. So in this chatting application, we
create the sharing images between multiple clients based on the file sharing services. The clients
will enter the chatroom when the server is up and they can chat and share images.

We have decided to use Java Language to create our project. Using Java, we have build a
terminal and GUI for Client and Server. A server computer can manage several clients
simultaneously, whereas one client can be connected to several servers at a time, each providing
a different set of services. Then, the client must enter their nickname to register into the server
with the specific port number given. So, all client will be in the same chatroom, if they registered
with the similar port number. After they have entering the chatroom, they can chatting and
sharing images among them.

4.0 METHODOLOGY

Since we are using Java Language to produce Client/Server terminal for our chatroom,
here we also include the code for attaching image in the chatroom:
BufferedImage
For transferring image in the chat application, there are some line of code that has to be added.
The image will be send to the server and it will broadcasted to the other clients using socket.
Java BufferedImage class is a subclass of Image class. It is used to handle and manipulate the
image data. It also need ImageIO which is the class containing static convenience methods for
locating ImageReaders and ImageWriters, and performing simple encoding and decoding. The
BufferedImage coding is located in the Server program to run and it is output in a Client
program.
Sample code:
In Server:
BufferedImage
img=[Link]([Link]([Link]
tream()));
[Link]("Image received!!!!");
[Link](img);

In Client:
ImageIcon img1=new ImageIcon("[Link]");
Image img = [Link]();
Image newimg = [Link](100, 120
[Link].SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);

bimg = [Link](new File("D:\picture\[Link]"));


[Link](bimg,"JPG",[Link]());
[Link]("Image sent!!!!");

5.0 TOOLS (EG. EQUIPMENT, HARDWARE, ETC.) REQUIRED


Tools

Description

1. Microsoft Windows

Operating System of student laptop

2. Eclipse Luna 4.4.1

Main Software for creating the Client/Server


terminal

6.0 RESULTS
6.1 PROJECT DELIVERABLES
In this section it will contain the information of the developed transferring image using
java. We have produce the prototype using Java Language by Eclipse. The coding has been
executed successfully. The application should consisted the following pages;
1. Chat Client Window
2. Chat Server Window
3. Chat Message Window

The screenshots:
1. Chat Server Window

Server interface

2. Chat Server Window

The client need to enter username and port number. The other client who wants to
join the conversation need to use the same port number.

3. Chat Server Window


6

After all the clients have connected to the server, all the conversation will be
appeared at the server interface

4. Chat Server Window

Each of every clients will be able to receive message from everyone.

5. Chat Client Window

If the client wants to exit from the chatroom, they have to click the logout button

6. Chat Server Window


9

The server will receive the action and notify other clients.

7. Chat Client Window

10

To know the available chatters, the client might click on Who is in button.

8. Chat Client Window


11

The attach picture button is for transferring image to other clients through the
server. The server will notify the client whether the image is receive or not and then
broadcast to other client to view or download.

7. 0 CONCLUSION
Chatting room Application is one of the Architectural Model in Distributed Computing.
We have almost successfull create the Chat Room and transferring the image between the
chatters. We also have create the chat room using Java that have Client and Server terminal and
using th BufferedImage method.

12

13

APPENDIX
Coding
[Link]

import [Link];
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

import [Link];

public class Server {

private static int uniqueId;


private ArrayList<ClientThread> al;
private ServerGUI sg;
private SimpleDateFormat sdf;
private int port;
private boolean keepGoing;
private Socket socket;

public Server(int port) {


this(port, null);
}

public Server(int port, ServerGUI sg) {


[Link] = sg;
[Link] = port;
sdf = new SimpleDateFormat("HH:mm:ss");
al = new ArrayList<ClientThread>();
14

public void start() {


keepGoing = true;
try
{
ServerSocket serverSocket = new ServerSocket(port);

while(keepGoing)
{
display("Server waiting for Clients on port " + port + ".");

Socket socket = [Link]();

if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
[Link](t);
[Link]();
}
try {
[Link]();
for(int i = 0; i < [Link](); ++i) {
ClientThread tc = [Link](i);
try {
[Link]();
[Link]();
[Link]();
}
catch(IOException ioE) {

15

}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
catch (IOException e) {
String msg = [Link](new Date()) + " Exception on new ServerSocket: " +
e + "\n";
display(msg);
}
}

protected void stop() {


keepGoing = false;

try {
new Socket("localhost", port);
}
catch(Exception e) {

}
}

private void display(String msg) {


String time = [Link](new Date()) + " " + msg;
if(sg == null)
[Link](time);
else

16

[Link](time + "\n");
}

private synchronized void broadcast(String message) {


String time = [Link](new Date());
String messageLf = time + " " + message + "\n";
if(sg == null)
[Link](messageLf);
else
[Link](messageLf);

// append in the room window

for(int i = [Link](); --i >= 0;) {


ClientThread ct = [Link](i);
if(![Link](messageLf)) {
[Link](i);
display("Disconnected Client " + [Link] + "
removed from list.");
}
}
}

synchronized void remove(int id) {


for(int i = 0; i < [Link](); ++i) {
ClientThread ct = [Link](i);
if([Link] == id) {
[Link](i);
return;
}
}
}

17

public static void main(String[] args) {


int portNumber = 1111;
switch([Link]) {
case 1:
try {
portNumber = [Link](args[0]);
}
catch(Exception e) {
[Link]("Invalid port number.");
[Link]("Usage is: > java Server
[portNumber]");
return;
}
case 0:
break;
default:
[Link]("Usage is: > java Server
[portNumber]");
return;

}
Server server = new Server(portNumber);
[Link]();
}

class ClientThread extends Thread {

Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
int id;
18

String username;
ChatMessage cm;
String date;

ClientThread(Socket socket) {
id = ++uniqueId;
[Link] = socket;
[Link]("Thread trying to create Object Input/Output
Streams");
try
{
sOutput = new
ObjectOutputStream([Link]());
sInput = new
ObjectInputStream([Link]());
username = (String) [Link]();
display(username + " just connected.");
}
catch (IOException e) {
display("Exception creating new Input/output Streams: " +
e);
return;
}
catch (ClassNotFoundException e) {
}
date = new Date().toString() + "\n";
}

public void run() {


boolean keepGoing = true;
while(keepGoing) {
try {
19

cm = (ChatMessage) [Link]();
}
catch (IOException e) {
display(username + " Exception reading Streams: "
+ e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
String message = [Link]();

switch([Link]()) {

case [Link]:
broadcast(username + ": " + message);
break;
case [Link]:
display(username + " disconnected with a LOGOUT
message.");
keepGoing = false;
break;
case [Link]:
writeMsg("List of the users connected at " +
[Link](new Date()) + "\n");
for(int i = 0; i < [Link](); ++i) {
ClientThread ct = [Link](i);
writeMsg((i+1) + ") " + [Link] + "
since " + [Link]);
}break;
case [Link]:
[Link]("IMAGE IS RECEIVED.");

20

//writeMsg("List of the users connected at " +


[Link](new Date()) + "\n");

break;
}
}
remove(id);
close();
}

private void close() {


try {
if(sOutput != null) [Link]();
}
catch(Exception e) {}
try {
if(sInput != null) [Link]();
}
catch(Exception e) {};
try {
if(socket != null) [Link]();
}
catch (Exception e) {}
}

private boolean writeMsg(String msg) {


if(![Link]()) {
close();
return false;
}

21

try {
[Link](msg);
}
catch(IOException e) {
display("Error sending message to " + username);
display([Link]());
}
return true;
}
}
}

[Link]

import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link].*;

public class Client {


Image newimg;
BufferedImage bimg;
byte[] bytes;

private ObjectInputStream sInput;

// to read from the socket

private ObjectOutputStream sOutput;

// to write on the socket

private Socket socket;

22

private ClientGUI cg;

private String server, username;


private int port;

Client(String server, int port, String username) {

this(server, port, username, null);


}

Client(String server, int port, String username, ClientGUI cg) {


[Link] = server;
[Link] = port;
[Link] = username;

[Link] = cg;
}

public boolean start() {

try {
socket = new Socket(server, port);
}

catch(Exception ec) {
display("Error connectiong to server:" + ec);
23

return false;
}

String msg = "Connection accepted " + [Link]() + ":" +


[Link]();
display(msg);

try
{
sInput = new ObjectInputStream([Link]());
sOutput = new ObjectOutputStream([Link]());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}

new ListenFromServer().start();

try
{
[Link](username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}

24

return true;
}

private void display(String msg) {


if(cg == null)
[Link](msg);
else
[Link](msg + "\n");
}

void sendMessage(ChatMessage msg) {


try {
[Link](msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}

private void disconnect() {


try {
if(sInput != null) [Link]();
}
catch(Exception e) {}
try {
if(sOutput != null) [Link]();
}
catch(Exception e) {}
25

try{
if(socket != null) [Link]();
}
catch(Exception e) {}

if(cg != null)
[Link]();

public static void main(String[] args) {

int portNumber = 1111;


String serverAddress = "localhost";
String userName = "Anonymous";

switch([Link]) {
case 3:
serverAddress = args[2];
case 2:
try {
portNumber = [Link](args[1]);
}
catch(Exception e) {
[Link]("Invalid port number.");
[Link]("Usage is: > java Client
[username] [portNumber] [serverAddress]");
return;
}

26

case 1:
userName = args[0];
case 0:
break;
default:
[Link]("Usage is: > java Client [username]
[portNumber] {serverAddress]");
return;
}

ImageIcon img1=new ImageIcon("[Link]");


Image img = [Link]();
Image newimg = [Link](100, 120,
[Link].SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);

bimg = [Link](new File("D:/gambar weh/nak/IMG_3799.JPG"));


[Link](bimg,"JPG",[Link]());
[Link]("Image sent!!!!");

Client client = new Client(serverAddress, portNumber, userName);

if(![Link]())
return;

Scanner scan = new Scanner([Link]);

while(true) {
[Link]("> ");

String msg = [Link]();


27

if([Link]("LOGOUT")) {
[Link](new
ChatMessage([Link], ""));

break;
}
else if([Link]("WHOISIN")) {
[Link](new
ChatMessage([Link], ""));
}
else if([Link]("AttachPic")) {
[Link](new
ChatMessage([Link], ""));
}
else {
[Link](new
ChatMessage([Link], msg));
}
}

[Link]();
}

class ListenFromServer extends Thread {

public void run() {


while(true) {
try {
String msg = (String) [Link]();
if(cg == null) {
[Link](msg);
28

[Link]("> ");
}
else {
[Link](msg);
}
}
catch(IOException e) {
display("Server has close the connection: " + e);
if(cg != null)
[Link]();
break;
}
catch(ClassNotFoundException e2) {
}
}
}
}
}

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class ServerGUI extends JFrame implements ActionListener, WindowListener {

private static final long serialVersionUID = 1L;


29

private JButton stopStart;


private JTextArea chat, event;
private JTextField tPortNumber;
private Server server;

ServerGUI(int port) {
super("Chat Server");
server = null;
JPanel north = new JPanel();
[Link](new JLabel("Port number: "));
tPortNumber = new JTextField(" " + port);
[Link](tPortNumber);
stopStart = new JButton("Start");
[Link](this);
[Link](stopStart);
add(north, [Link]);

JPanel center = new JPanel(new GridLayout(2,1));


chat = new JTextArea(80,80);
[Link](false);
appendRoom("Chat room.\n");
[Link](new JScrollPane(chat));
event = new JTextArea(80,80);
[Link](false);
appendEvent("Events log.\n");
[Link](new JScrollPane(event));
add(center);

addWindowListener(this);
setSize(400, 600);
30

setVisible(true);
}

void appendRoom(String str) {


[Link](str);
[Link]([Link]().length() - 1);
}
void appendEvent(String str) {
[Link](str);
[Link]([Link]().length() - 1);

public void actionPerformed(ActionEvent e) {


if(server != null) {
[Link]();
server = null;
[Link](true);
[Link]("Start");
return;
}

int port;
try {
port = [Link]([Link]().trim());
}
catch(Exception er) {
appendEvent("Invalid port number");
31

return;
}
server = new Server(port, this);
new ServerRunning().start();
[Link]("Stop");
[Link](false);
}

public static void main(String[] arg) {


new ServerGUI(1111);
}

public void windowClosing(WindowEvent e) {


if(server != null) {
try {
[Link]();
}
catch(Exception eClose) {
}
server = null;
}
dispose();
[Link](0);
}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
32

class ServerRunning extends Thread {


public void run() {
[Link]();
[Link]("Start");
[Link](true);
appendEvent("Server crashed\n");
server = null;
}
}

[Link]

import [Link].*;
import [Link].*;
import [Link].*;

public class ClientGUI extends JFrame implements ActionListener {

private static final long serialVersionUID = 1L;


private JLabel label;
private JTextField tf;
private JTextField tfServer, tfPort;
private JButton login, logout, whoIsIn, AttachPic;
private JTextArea ta;
private boolean connected;
private Client client;
private int defaultPort;
33

private String defaultHost;

ClientGUI(String host, int port) {

super("Chat Client");
defaultPort = port;
defaultHost = host;

JPanel northPanel = new JPanel(new GridLayout(3,1));


JPanel serverAndPort = new JPanel(new GridLayout(1,5, 1, 3));
tfServer = new JTextField(host);
tfPort = new JTextField("" + port);
[Link]([Link]);

[Link](new JLabel("Server Address: "));


[Link](tfServer);
[Link](new JLabel("Port Number: "));
[Link](tfPort);
[Link](new JLabel(""));
[Link](serverAndPort);

label = new JLabel("Enter your username below",


[Link]);
[Link](label);
tf = new JTextField("Enter your name here");
[Link]([Link]);
[Link](tf);
add(northPanel, [Link]);

ta = new JTextArea("Hi, you're in Kotak Borak !\n", 80, 80);


JPanel centerPanel = new JPanel(new GridLayout(1,1));

34

[Link](new JScrollPane(ta));
[Link](false);
add(centerPanel, [Link]);

login = new JButton("Login");


[Link](this);
[Link]([Link]);
logout = new JButton("Logout");
[Link](this);
[Link](false);
[Link]([Link]);
whoIsIn = new JButton("Who is in");
[Link](this);
[Link](false);
[Link]([Link]);
AttachPic = new JButton("Attach Picture");
[Link](this);
[Link](false);
[Link]([Link]);

JPanel southPanel = new JPanel();


[Link](login);
[Link](logout);
[Link](whoIsIn);
[Link](AttachPic);
add(southPanel, [Link]);

setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
[Link]();
35

void append(String str) {


[Link](str);
[Link]([Link]().length() - 1);
}
void connectionFailed() {
[Link](true);
[Link](false);
[Link](false);
[Link](false);
[Link]("Enter your username below");
[Link]("Enter your name");
[Link]("" + defaultPort);
[Link](defaultHost);
[Link](false);
[Link](false);
[Link](this);
connected = false;
}

public void actionPerformed(ActionEvent e) {


Object o = [Link]();
if(o == logout) {
[Link](new ChatMessage([Link],
""));
return;
}
if(o == whoIsIn) {

36

[Link](new ChatMessage([Link],
""));
return;
}
if(o == AttachPic) {
[Link](new ChatMessage([Link],
""));
return;
}
if(connected) {
[Link](new ChatMessage([Link],
[Link]()));
[Link]("");
return;
}

if(o == login) {
String username = [Link]().trim();
if([Link]() == 0)
return;
String server = [Link]().trim();
if([Link]() == 0)
return;
String portNumber = [Link]().trim();
if([Link]() == 0)
return;
int port = 0;
try {
port = [Link](portNumber);
}
catch(Exception en) {
37

return;
}

client = new Client(server, port, username, this);


if(![Link]())
return;
[Link]("");
[Link]("Enter your message below");
connected = true;

[Link](false);
[Link](true);
[Link](true);
[Link](true);
[Link](false);
[Link](false);
[Link](this);
}

public static void main(String[] args) {


new ClientGUI("localhost", 1111);
}

}
[Link]
import [Link].*;
public class ChatMessage implements Serializable {
protected static final long serialVersionUID = 1112122200L;
38

static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2, AttachPic = 3;


private int type;
private String message;
ChatMessage(int type, String message) {
[Link] = type;
[Link] = message;
}
int getType() {
return type;
}
String getMessage() {
return message;
}
}

39

Common questions

Powered by AI

Sockets play a crucial role in the Java-based chat application's client-server architecture by providing the necessary endpoints for communication between clients and the server. They enable the transmission of messages and image data over a network, facilitating real-time interaction within the chatroom. Sockets allow the server to accept incoming client connections and manage data streams, ensuring that all clients can send and receive data efficiently .

The benefits of using the Java BufferedImage class in a distributed image transfer application include its ability to efficiently manage image data, allowing for high-quality rendering and manipulation across different platforms. This class supports various image operations, enabling custom scaling and formatting needed in distributed systems. However, its limitations can include performance overhead in managing large images and the need for compatibility checks with different client devices to ensure images are displayed correctly. Appropriate management of memory and processing resources is crucial, as the class can be resource-intensive when scaling or converting images .

The client-server interaction model supports scalability in a distributed chat application using Java by allowing the server to handle multiple client connections simultaneously. With proper resource management and efficient threading, the server can scale up to accommodate increased numbers of users without significant degradation of service. Java's robust socket programming and thread management provide the flexibility needed to manage this scaling. Additionally, features like synchronized methods and handling of concurrent streams help maintain performance as user load increases .

Client/server architecture facilitates file sharing and communication by allowing a central server to host, deliver, and manage resources which are then consumed by client devices. In a distributed computing system like the described chat application, the server establishes a connection with multiple clients over a network, providing them with services such as file sharing and messaging. This model allows the server to broadcast messages and images sent from one client to others, using Java for handling communication protocols and image processing .

The Java BufferedImage class contributes to image data manipulation and transfer by providing an intricate framework for handling and processing image data. It acts as a more versatile subclass of the Image class, capable of producing optimized, platform-independent graphics. Within the chat application, it interfaces with the ImageIO class to read and write images between clients and the server, ensuring that images are correctly transferred and displayed without loss of quality. The BufferedImage's ability to scale and modify images also aids in fitting images to the necessary display requirements on the client side .

Java enhances the capabilities of distributed applications for file transfer by providing a robust framework for handling network communications and data manipulation. The BufferedImage class, for example, allows for efficient image handling and processing, while Java's socket programming enables reliable data exchange between clients and servers. Additionally, the use of Java ImageIO supports easy encoding and decoding of image data, facilitating the smooth transfer of multimedia files within the chat application .

The chatroom application ensures synchronization and consistent communication among multiple clients by using a single server to manage all client connections and broadcasts. This server maintains a list of connected clients and uses synchronized methods to handle message broadcasts and updates. When a message is received from one client, the server broadcasts it to all others, ensuring that each client receives the message in real-time. This broadcast mechanism and the server's control over the data flow help maintain consistency across the chatroom .

Implementing a client-server chat application with image sharing capabilities using Java presents several challenges. These include managing concurrent connections and ensuring synchronization between multiple clients, handling network instability or disconnections, and efficiently transferring image files without data loss or degradation. Moreover, it requires robust error handling to manage exceptions during stream operations, as well as implementing interfaces that provide a seamless user experience across different client devices .

To facilitate image attachment features within the chat application, methodologies such as utilizing the Java BufferedImage and ImageIO classes are used. These classes allow for the efficient reading, manipulation, and writing of image data exchanged between the server and clients. The server-side code includes logic to handle incoming image streams, convert them into BufferedImage objects, and then relay them to other clients via sockets. This process requires correctly managing the image data format and ensuring compatibility with client-side image viewers .

The Java-based chat application employs several strategies to handle exceptions in client-server communication. These include robust error handling mechanisms embedded in the code, such as try-catch blocks wrapping socket connections and I/O operations to manage potential disruptions. The application handles specific exceptions like IOException during stream operations and implements fallback procedures such as automatic retry for transient errors or clean resource closure in persistent problems. Additionally, user feedback mechanisms like logging errors to the server console help diagnose issues in real-time .

You might also like