Sei sulla pagina 1di 40

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=ImageIO.read(ImageIO.createImageInputStream(socket.getInputS
tream()));
System.out.println("Image received!!!!");
lblimg.setIcon(img);

In Client:
ImageIcon img1=new ImageIcon("PIC2.jpg");
Image img = img1.getImage();
Image newimg = img.getScaledInstance(100, 120
java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);

bimg = ImageIO.read(new File("D:\picture\DSC02503.JPG"));


ImageIO.write(bimg,"JPG",client.getOutputStream());
System.out.println("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
Server.java

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;

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) {


this.sg = sg;
this.port = 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 = serverSocket.accept();

if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
al.add(t);
t.start();
}
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {

15

}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
catch (IOException e) {
String msg = sdf.format(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 = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else

16

sg.appendEvent(time + "\n");
}

private synchronized void broadcast(String message) {


String time = sdf.format(new Date());
String messageLf = time + " " + message + "\n";
if(sg == null)
System.out.print(messageLf);
else
sg.appendRoom(messageLf);

// append in the room window

for(int i = al.size(); --i >= 0;) {


ClientThread ct = al.get(i);
if(!ct.writeMsg(messageLf)) {
al.remove(i);
display("Disconnected Client " + ct.username + "
removed from list.");
}
}
}

synchronized void remove(int id) {


for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
if(ct.id == id) {
al.remove(i);
return;
}
}
}

17

public static void main(String[] args) {


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

}
Server server = new Server(portNumber);
server.start();
}

class ClientThread extends Thread {

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

String username;
ChatMessage cm;
String date;

ClientThread(Socket socket) {
id = ++uniqueId;
this.socket = socket;
System.out.println("Thread trying to create Object Input/Output
Streams");
try
{
sOutput = new
ObjectOutputStream(socket.getOutputStream());
sInput = new
ObjectInputStream(socket.getInputStream());
username = (String) sInput.readObject();
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) sInput.readObject();
}
catch (IOException e) {
display(username + " Exception reading Streams: "
+ e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
String message = cm.getMessage();

switch(cm.getType()) {

case ChatMessage.MESSAGE:
broadcast(username + ": " + message);
break;
case ChatMessage.LOGOUT:
display(username + " disconnected with a LOGOUT
message.");
keepGoing = false;
break;
case ChatMessage.WHOISIN:
writeMsg("List of the users connected at " +
sdf.format(new Date()) + "\n");
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
writeMsg((i+1) + ") " + ct.username + "
since " + ct.date);
}break;
case ChatMessage.AttachPic:
System.out.println("IMAGE IS RECEIVED.");

20

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


sdf.format(new Date()) + "\n");

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

private void close() {


try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}

private boolean writeMsg(String msg) {


if(!socket.isConnected()) {
close();
return false;
}

21

try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Error sending message to " + username);
display(e.toString());
}
return true;
}
}
}

Client.java

import java.net.*;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

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) {


this.server = server;
this.port = port;
this.username = username;

this.cg = 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 " + socket.getInetAddress() + ":" +


socket.getPort();
display(msg);

try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}

new ListenFromServer().start();

try
{
sOutput.writeObject(username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}

24

return true;
}

private void display(String msg) {


if(cg == null)
System.out.println(msg);
else
cg.append(msg + "\n");
}

void sendMessage(ChatMessage msg) {


try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}

private void disconnect() {


try {
if(sInput != null) sInput.close();
}
catch(Exception e) {}
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
25

try{
if(socket != null) socket.close();
}
catch(Exception e) {}

if(cg != null)
cg.connectionFailed();

public static void main(String[] args) {

int portNumber = 1111;


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

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

26

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

ImageIcon img1=new ImageIcon("Ashish.jpg");


Image img = img1.getImage();
Image newimg = img.getScaledInstance(100, 120,
java.awt.Image.SCALE_SMOOTH);
ImageIcon newIcon = new ImageIcon(newimg);

bimg = ImageIO.read(new File("D:/gambar weh/nak/IMG_3799.JPG"));


ImageIO.write(bimg,"JPG",client.getOutputStream());
System.out.println("Image sent!!!!");

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

if(!client.start())
return;

Scanner scan = new Scanner(System.in);

while(true) {
System.out.print("> ");

String msg = scan.nextLine();


27

if(msg.equalsIgnoreCase("LOGOUT")) {
client.sendMessage(new
ChatMessage(ChatMessage.LOGOUT, ""));

break;
}
else if(msg.equalsIgnoreCase("WHOISIN")) {
client.sendMessage(new
ChatMessage(ChatMessage.WHOISIN, ""));
}
else if(msg.equalsIgnoreCase("AttachPic")) {
client.sendMessage(new
ChatMessage(ChatMessage.AttachPic, ""));
}
else {
client.sendMessage(new
ChatMessage(ChatMessage.MESSAGE, msg));
}
}

client.disconnect();
}

class ListenFromServer extends Thread {

public void run() {


while(true) {
try {
String msg = (String) sInput.readObject();
if(cg == null) {
System.out.println(msg);
28

System.out.print("> ");
}
else {
cg.append(msg);
}
}
catch(IOException e) {
display("Server has close the connection: " + e);
if(cg != null)
cg.connectionFailed();
break;
}
catch(ClassNotFoundException e2) {
}
}
}
}
}

ServerGui.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFileChooser;
import java.io.File;

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();
north.add(new JLabel("Port number: "));
tPortNumber = new JTextField(" " + port);
north.add(tPortNumber);
stopStart = new JButton("Start");
stopStart.addActionListener(this);
north.add(stopStart);
add(north, BorderLayout.NORTH);

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


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

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

setVisible(true);
}

void appendRoom(String str) {


chat.append(str);
chat.setCaretPosition(chat.getText().length() - 1);
}
void appendEvent(String str) {
event.append(str);
event.setCaretPosition(chat.getText().length() - 1);

public void actionPerformed(ActionEvent e) {


if(server != null) {
server.stop();
server = null;
tPortNumber.setEditable(true);
stopStart.setText("Start");
return;
}

int port;
try {
port = Integer.parseInt(tPortNumber.getText().trim());
}
catch(Exception er) {
appendEvent("Invalid port number");
31

return;
}
server = new Server(port, this);
new ServerRunning().start();
stopStart.setText("Stop");
tPortNumber.setEditable(false);
}

public static void main(String[] arg) {


new ServerGUI(1111);
}

public void windowClosing(WindowEvent e) {


if(server != null) {
try {
server.stop();
}
catch(Exception eClose) {
}
server = null;
}
dispose();
System.exit(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() {
server.start();
stopStart.setText("Start");
tPortNumber.setEditable(true);
appendEvent("Server crashed\n");
server = null;
}
}

ClientGUI.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

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);
tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

serverAndPort.add(new JLabel("Server Address: "));


serverAndPort.add(tfServer);
serverAndPort.add(new JLabel("Port Number: "));
serverAndPort.add(tfPort);
serverAndPort.add(new JLabel(""));
northPanel.add(serverAndPort);

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


SwingConstants.LEFT);
northPanel.add(label);
tf = new JTextField("Enter your name here");
tf.setBackground(Color.PINK);
northPanel.add(tf);
add(northPanel, BorderLayout.NORTH);

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


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

34

centerPanel.add(new JScrollPane(ta));
ta.setEditable(false);
add(centerPanel, BorderLayout.CENTER);

login = new JButton("Login");


login.addActionListener(this);
login.setBackground(Color.BLUE);
logout = new JButton("Logout");
logout.addActionListener(this);
logout.setEnabled(false);
logout.setBackground(Color.BLUE);
whoIsIn = new JButton("Who is in");
whoIsIn.addActionListener(this);
whoIsIn.setEnabled(false);
whoIsIn.setBackground(Color.BLUE);
AttachPic = new JButton("Attach Picture");
AttachPic.addActionListener(this);
AttachPic.setEnabled(false);
AttachPic.setBackground(Color.BLUE);

JPanel southPanel = new JPanel();


southPanel.add(login);
southPanel.add(logout);
southPanel.add(whoIsIn);
southPanel.add(AttachPic);
add(southPanel, BorderLayout.SOUTH);

setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
tf.requestFocus();
35

void append(String str) {


ta.append(str);
ta.setCaretPosition(ta.getText().length() - 1);
}
void connectionFailed() {
login.setEnabled(true);
logout.setEnabled(false);
whoIsIn.setEnabled(false);
AttachPic.setEnabled(false);
label.setText("Enter your username below");
tf.setText("Enter your name");
tfPort.setText("" + defaultPort);
tfServer.setText(defaultHost);
tfServer.setEditable(false);
tfPort.setEditable(false);
tf.removeActionListener(this);
connected = false;
}

public void actionPerformed(ActionEvent e) {


Object o = e.getSource();
if(o == logout) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT,
""));
return;
}
if(o == whoIsIn) {

36

client.sendMessage(new ChatMessage(ChatMessage.WHOISIN,
""));
return;
}
if(o == AttachPic) {
client.sendMessage(new ChatMessage(ChatMessage.AttachPic,
""));
return;
}
if(connected) {
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE,
tf.getText()));
tf.setText("");
return;
}

if(o == login) {
String username = tf.getText().trim();
if(username.length() == 0)
return;
String server = tfServer.getText().trim();
if(server.length() == 0)
return;
String portNumber = tfPort.getText().trim();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
37

return;
}

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


if(!client.start())
return;
tf.setText("");
label.setText("Enter your message below");
connected = true;

login.setEnabled(false);
logout.setEnabled(true);
whoIsIn.setEnabled(true);
AttachPic.setEnabled(true);
tfServer.setEditable(false);
tfPort.setEditable(false);
tf.addActionListener(this);
}

public static void main(String[] args) {


new ClientGUI("localhost", 1111);
}

}
ChatMessage.java
import java.io.*;
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) {
this.type = type;
this.message = message;
}
int getType() {
return type;
}
String getMessage() {
return message;
}
}

39

Potrebbero piacerti anche