SlideShare a Scribd company logo
TUGAS
Membuat Program MultiClient Chatting Client-Server
Menggunakan Bahasa Pemrograman Java Berbasis Grafis
Oleh :
M. Ichsan Barokah
061130701305
6CD
JURUSAN TEKNIK KOMPUTER
POLITEKNIK NEGERI SRIWIJAYA
PALEMBANG
Chatting memungkinkan kita untuk selalu bisa berkomunikasi
walaupun kita tidak berada bersamanya di suatu tempat. Aplikasi chatting
merupakan suatu aplikasi yang memungkinkan pengguna (client)
berkomunikasi teks secara langsung (Real Time) dengan pengguna lain dengan
menggunakan media yang ada.
Hal yang harus dilakukan kita terlebih dahulu untuk menjalankan program
chatting ialah melakukan setting alamat IP pada masing-masing client.
Setelah melakukan konfigurasi IP pada masing-masingikomputer
kemudian kita juga harus memastikan bahwa firewall pada masing-masing
komputer harus diaktifkan karena pada beberapa kasus program ini tidak dapat saling
terkoneksi akibat firewall yang aktif pada sistem operasinya.
Berikut adalah listing program MultiClient Chatting Client-Server berbasis
grafis
 ChatServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static int uniqueId;
private ArrayList<ChatServer.ClientThread> clients;
private int port;
private boolean keepGoing;
public ChatServer() {
this.port = 9999;
clients = new ArrayList();
}
public void start() {
keepGoing = true;
try {
ServerSocket serverSocket = new ServerSocket(port);
while (keepGoing) {
System.out.println("ChatServer waiting for Clients
on port " + port + ".");
Socket socket = serverSocket.accept();
if (!keepGoing) {
break;
}
ChatServer.ClientThread t = new
ChatServer.ClientThread(socket);
clients.add(t);
t.start();
send("login~" + t.username + "~" + t.username + "
sedang login...~Server~n");
}
try {
serverSocket.close();
for (int i = 0; i < clients.size(); ++i) {
ChatServer.ClientThread tc = clients.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
} catch (IOException ioE) {
}
}
} catch (Exception e) {
System.out.println("Exception closing the server
and clients: " + e);
}
} catch (IOException e) {
String msg = "Exception on new ServerSocket: " + e +
"n";
System.out.println(msg);
}
}
private synchronized void send(String message) {
for (int i = clients.size(); --i >= 0;) {
ChatServer.ClientThread ct = clients.get(i);
if (!ct.writeMsg(message)) {
clients.remove(i);
System.out.println("Disconnected Client " +
ct.username + " removed from list.");
}
}
}
private String getClients() {
String s = "";
for (ClientThread clientThread : clients) {
s += clientThread.username + ":";
}
s += "---";
System.out.println(s);
return s;
}
private synchronized void remove(int id) {
for (int i = 0; i < clients.size(); ++i) {
ChatServer.ClientThread ct = clients.get(i);
if (ct.id == id) {
clients.remove(i);
return;
}
}
}
public static void main(String[] args) {
ChatServer server = new ChatServer();
server.start();
}
private class ClientThread extends Thread {
private Socket socket;
private ObjectInputStream sInput;
private ObjectOutputStream sOutput;
private int id;
private String username;
public ClientThread(Socket socket) {
id = ++uniqueId;
this.socket = socket;
System.out.println("Menciptakan Object Input/Output
Streams");
try {
sOutput = new
ObjectOutputStream(socket.getOutputStream());
sInput = new
ObjectInputStream(socket.getInputStream());
String message = (String) sInput.readObject();
username = message.split("~")[1];
System.out.println(username + " masuk.");
} catch (IOException e) {
System.out.println("Exception creating new
Input/output Streams: " + e);
} catch (ClassNotFoundException e) {
}
}
@Override
public void run() {
boolean keepGoing = true;
while (keepGoing) {
String message;
try {
message = sInput.readObject().toString();
} catch (IOException e) {
System.out.println(username + " Exception
reading Streams: " + e);
break;
} catch (ClassNotFoundException e2) {
break;
}
String type = message.split("~")[0];
String pengirim = message.split("~")[1];
String text = message.split("~")[2];
String kepada = message.split("~")[3];
String response;
switch (type) {
case "postText":
response = "recieveText~" + pengirim + "~"
+ text + "~" + kepada + "~n";
send(response);
break;
case "postPrivateText":
response = "recievePrivateText~" +
pengirim + "~" + text + "~" + kepada + "~n";
send(response);
break;
case "login":
response = "login~" + pengirim + "~" +
text + "~" + kepada + "~n";
send(response);
break;
case "logout":
response = "logout~" + pengirim + "~" +
text + "~" + kepada + "~n";
send(response);
break;
case "list":
response = "list~server~" + getClients() +
"~ ~ ~ ~ ~n";
send(response);
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;
}
try {
sOutput.writeObject(msg);
} catch (IOException e) {
System.out.println("Error sending message to " +
username);
System.out.println(e.toString());
}
return true;
}
}
}
ChatClient.java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableModel;
public class ChatClient extends javax.swing.JFrame {
/**
* Creates new form ChatClient
*/
private ObjectInputStream input;
private ObjectOutputStream output;
private Socket socket;
private String server, username;
private int port;
private List<String> clients;
public ChatClient() {
clients = new ArrayList();
initComponents();
}
public boolean start() {
try {
socket = new Socket(server, port);
} catch (Exception ec) {
System.out.println("Error connectiong to server:" +
ec);
return false;
}
String msg = "Connection accepted " +
socket.getInetAddress() + ":" + socket.getPort();
System.out.println(msg);
try {
input = new
ObjectInputStream(socket.getInputStream());
output = new
ObjectOutputStream(socket.getOutputStream());
} catch (IOException eIO) {
System.out.println("Exception creating new
Input/output Streams: " + eIO);
return false;
}
new ChatClient.ListenFromServer().start();
try {
output.writeObject("login~" + username + "~" +
username + " sedang login...~server~n");
output.writeObject("list~" + username + "~" + username
+ " sedang login...~server~n");
} catch (IOException eIO) {
System.out.println("Exception doing login : " + eIO);
disconnect();
return false;
}
return true;
}
private void disconnect() {
try {
// TODO add your handling code here:
output.writeObject("logout~" + username + "~" +
username + " sudah logout...~Server~n");
} catch (IOException ex) {
//Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, ex);
}
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
}
try {
if (output != null) {
output.close();
}
} catch (Exception e) {
}
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
}
}
/**
* This method is called from within the constructor to
initialize the form.
* WARNING: Do NOT modify this code. The content of this
method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated
Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
viewTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
clientTable = new javax.swing.JTable();
postTextField = new javax.swing.JTextField();
kirimButton = new javax.swing.JButton();
lbljpg = new javax.swing.JLabel(new
ImageIcon("E:/rara.jpg"));
jLabel2 = new javax.swing.JLabel();
serverTextField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
portTextField = new javax.swing.JTextField();
masukButton = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
usernameTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE
);
viewTextArea.setEditable(false);
viewTextArea.setColumns(20);
viewTextArea.setLineWrap(true);
viewTextArea.setRows(5);
viewTextArea.setFocusable(false);
jScrollPane1.setViewportView(viewTextArea);
jScrollPane2.setViewportView(clientTable);
postTextField.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) {
postTextFieldActionPerformed(evt);
}
});
kirimButton.setText("Kirim");
kirimButton.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) {
kirimButtonActionPerformed(evt);
}
});
jLabel2.setText("Server");
serverTextField.setText("10.17.0.0");
jLabel3.setText("Port");
portTextField.setText("9999");
masukButton.setText("Masuk");
masukButton.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) {
masukButtonActionPerformed(evt);
}
});
jLabel4.setText("Username");
usernameTextField.setText("Rara Ariesta");
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(postTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(kirimButton))
.addComponent(jScrollPane1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 259,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lbljpg)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(serverTextField,
javax.swing.GroupLayout.PREFERRED_SIZE, 167,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(portTextField,
javax.swing.GroupLayout.PREFERRED_SIZE, 46,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(usernameTextField,
javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addComponent(masukButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.BASELINE)
.addComponent(lbljpg)
.addComponent(jLabel2)
.addComponent(serverTextField,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(portTextField,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(masukButton)
.addComponent(jLabel4)
.addComponent(usernameTextField,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING)
.addComponent(jScrollPane2,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE
D)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.BASELINE)
.addComponent(postTextField,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(kirimButton))))
.addContainerGap())
);
pack();
}// </editor-fold>
private void
masukButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.server = serverTextField.getText();
this.port = new Integer(portTextField.getText());
this.username = usernameTextField.getText();
start();
}
private void
kirimButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String message = "postText~" + username + "~" +
postTextField.getText() + "~all~n";
output.writeObject(message);
postTextField.setText("");
} catch (IOException ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private void
postTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
kirimButtonActionPerformed(evt);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and
feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available,
stay with the default look and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/pla
f.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log
(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log
(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log
(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log
(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ChatClient().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable clientTable;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton kirimButton;
private javax.swing.JButton masukButton;
private javax.swing.JTextField portTextField;
private javax.swing.JTextField postTextField;
private javax.swing.JTextField serverTextField;
private javax.swing.JTextField usernameTextField;
private javax.swing.JTextArea viewTextArea;
private JLabel lbljpg ;
// End of variables declaration
class ListenFromServer extends Thread {
@Override
public void run() {
while (true) {
try {
String msg = (String) input.readObject();
String res;
String type = msg.split("~")[0];
String pengirim = msg.split("~")[1];
String text = msg.split("~")[2];
String kepada = msg.split("~")[3];
switch (type) {
case "recieveText":
res = pengirim + ": " + text;
viewTextArea.setText(viewTextArea.getText() + res + "n");
break;
case "recievePrivateText":
res = pengirim + ": " + text;
if (kepada.equals(username)) {
viewTextArea.setText(viewTextArea.getText() + res + "n");
}
break;
case "login":
viewTextArea.setText(viewTextArea.getText() + pengirim + " sudah
login..." + "n");
clients.add(pengirim);
break;
case "logout":
viewTextArea.setText(viewTextArea.getText() + pengirim + " telah
logout..." + "n");
clients.remove(pengirim);
break;
case "list":
setTable(text);
break;
}
} catch (IOException e) {
System.out.println("Server has close the
connection: " + e);
break;
} catch (ClassNotFoundException e2) {
}
}
}
private void setTable(String text) {
int rows = text.split(":").length - 1;
Object[][] data = new Object[rows][1];
for (int i = 0; i < rows; i++) {
String t = text.split(":")[i];
data[i][0] = t;
}
String[] header = {"Clients"};
clientTable.setModel(new DefaultTableModel(data,
header));
}
}
}
Jika dijalankan maka tampilan akan seperti berikut:
Laporan multi client

More Related Content

What's hot

Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
Domenico Briganti
 
Programming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.ioProgramming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.io
Günter Obiltschnig
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
Suman Astani
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
Alexis Hassler
 
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Mumbai B.Sc.IT Study
 
Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]RootedCON
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
Aymeric Weinbach
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
PROIDEA
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
Fiyaz Hasan
 
Bh Usa 07 Butler And Kendall
Bh Usa 07 Butler And KendallBh Usa 07 Butler And Kendall
Bh Usa 07 Butler And KendallKarlFrank99
 
Revealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C ServerRevealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C Server
Senad Aruc
 
Vaadin7
Vaadin7Vaadin7
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?
gedoplan
 
OneTeam Media Server
OneTeam Media ServerOneTeam Media Server
OneTeam Media Server
Mickaël Rémond
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 

What's hot (20)

Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Programming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.ioProgramming IoT Gateways in JavaScript with macchina.io
Programming IoT Gateways in JavaScript with macchina.io
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
分散式系統
分散式系統分散式系統
分散式系統
 
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
 
Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]Hernan Ochoa - WCE Internals [RootedCON 2011]
Hernan Ochoa - WCE Internals [RootedCON 2011]
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Bh Usa 07 Butler And Kendall
Bh Usa 07 Butler And KendallBh Usa 07 Butler And Kendall
Bh Usa 07 Butler And Kendall
 
Revealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C ServerRevealing Unique MitB Builder C&C Server
Revealing Unique MitB Builder C&C Server
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?
 
OneTeam Media Server
OneTeam Media ServerOneTeam Media Server
OneTeam Media Server
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Dynamic virtual evironments
Dynamic virtual evironmentsDynamic virtual evironments
Dynamic virtual evironments
 
Java
JavaJava
Java
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 

Similar to Laporan multi client

Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
fashiongallery1
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Distributed systems
Distributed systemsDistributed systems
Distributed systems
Sonali Parab
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambaryoyomay93
 
Multi client
Multi clientMulti client
Multi clientAisy Cuyy
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Rara Ariesta
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
Rays Technologies
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
Ghadeer AlHasan
 
Networks lab
Networks labNetworks lab
Networks lab
svijiiii
 
Networks lab
Networks labNetworks lab
Networks labsvijiiii
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
hendriciraida
 
Multi client
Multi clientMulti client
Multi clientganteng8
 
Java 1
Java 1Java 1
Arduino and the real time web
Arduino and the real time webArduino and the real time web
Arduino and the real time web
Andrew Fisher
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
hendriciraida
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
Yakov Fain
 

Similar to Laporan multi client (20)

Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
java sockets
 java sockets java sockets
java sockets
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Distributed systems
Distributed systemsDistributed systems
Distributed systems
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
 
Multi client
Multi clientMulti client
Multi client
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
 
Networks lab
Networks labNetworks lab
Networks lab
 
Networks lab
Networks labNetworks lab
Networks lab
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
 
Multi client
Multi clientMulti client
Multi client
 
Network
NetworkNetwork
Network
 
Java 1
Java 1Java 1
Java 1
 
Arduino and the real time web
Arduino and the real time webArduino and the real time web
Arduino and the real time web
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 

Recently uploaded

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 

Recently uploaded (20)

Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 

Laporan multi client

  • 1. TUGAS Membuat Program MultiClient Chatting Client-Server Menggunakan Bahasa Pemrograman Java Berbasis Grafis Oleh : M. Ichsan Barokah 061130701305 6CD JURUSAN TEKNIK KOMPUTER POLITEKNIK NEGERI SRIWIJAYA PALEMBANG
  • 2. Chatting memungkinkan kita untuk selalu bisa berkomunikasi walaupun kita tidak berada bersamanya di suatu tempat. Aplikasi chatting merupakan suatu aplikasi yang memungkinkan pengguna (client) berkomunikasi teks secara langsung (Real Time) dengan pengguna lain dengan menggunakan media yang ada. Hal yang harus dilakukan kita terlebih dahulu untuk menjalankan program chatting ialah melakukan setting alamat IP pada masing-masing client. Setelah melakukan konfigurasi IP pada masing-masingikomputer kemudian kita juga harus memastikan bahwa firewall pada masing-masing komputer harus diaktifkan karena pada beberapa kasus program ini tidak dapat saling terkoneksi akibat firewall yang aktif pada sistem operasinya. Berikut adalah listing program MultiClient Chatting Client-Server berbasis grafis  ChatServer.java import java.io.*; import java.net.*; import java.util.*; public class ChatServer { private static int uniqueId; private ArrayList<ChatServer.ClientThread> clients; private int port; private boolean keepGoing; public ChatServer() { this.port = 9999; clients = new ArrayList(); }
  • 3. public void start() { keepGoing = true; try { ServerSocket serverSocket = new ServerSocket(port); while (keepGoing) { System.out.println("ChatServer waiting for Clients on port " + port + "."); Socket socket = serverSocket.accept(); if (!keepGoing) { break; } ChatServer.ClientThread t = new ChatServer.ClientThread(socket); clients.add(t); t.start(); send("login~" + t.username + "~" + t.username + " sedang login...~Server~n"); } try { serverSocket.close(); for (int i = 0; i < clients.size(); ++i) { ChatServer.ClientThread tc = clients.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); } catch (IOException ioE) { } }
  • 4. } catch (Exception e) { System.out.println("Exception closing the server and clients: " + e); } } catch (IOException e) { String msg = "Exception on new ServerSocket: " + e + "n"; System.out.println(msg); } } private synchronized void send(String message) { for (int i = clients.size(); --i >= 0;) { ChatServer.ClientThread ct = clients.get(i); if (!ct.writeMsg(message)) { clients.remove(i); System.out.println("Disconnected Client " + ct.username + " removed from list."); } } } private String getClients() { String s = ""; for (ClientThread clientThread : clients) { s += clientThread.username + ":"; } s += "---"; System.out.println(s);
  • 5. return s; } private synchronized void remove(int id) { for (int i = 0; i < clients.size(); ++i) { ChatServer.ClientThread ct = clients.get(i); if (ct.id == id) { clients.remove(i); return; } } } public static void main(String[] args) { ChatServer server = new ChatServer(); server.start(); } private class ClientThread extends Thread { private Socket socket; private ObjectInputStream sInput; private ObjectOutputStream sOutput; private int id; private String username; public ClientThread(Socket socket) { id = ++uniqueId;
  • 6. this.socket = socket; System.out.println("Menciptakan Object Input/Output Streams"); try { sOutput = new ObjectOutputStream(socket.getOutputStream()); sInput = new ObjectInputStream(socket.getInputStream()); String message = (String) sInput.readObject(); username = message.split("~")[1]; System.out.println(username + " masuk."); } catch (IOException e) { System.out.println("Exception creating new Input/output Streams: " + e); } catch (ClassNotFoundException e) { } } @Override public void run() { boolean keepGoing = true; while (keepGoing) { String message; try { message = sInput.readObject().toString(); } catch (IOException e) { System.out.println(username + " Exception reading Streams: " + e); break;
  • 7. } catch (ClassNotFoundException e2) { break; } String type = message.split("~")[0]; String pengirim = message.split("~")[1]; String text = message.split("~")[2]; String kepada = message.split("~")[3]; String response; switch (type) { case "postText": response = "recieveText~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "postPrivateText": response = "recievePrivateText~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "login": response = "login~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response); break; case "logout": response = "logout~" + pengirim + "~" + text + "~" + kepada + "~n"; send(response);
  • 8. break; case "list": response = "list~server~" + getClients() + "~ ~ ~ ~ ~n"; send(response); 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) {
  • 9. socket.close(); } } catch (Exception e) { } } private boolean writeMsg(String msg) { if (!socket.isConnected()) { close(); return false; } try { sOutput.writeObject(msg); } catch (IOException e) { System.out.println("Error sending message to " + username); System.out.println(e.toString()); } return true; } } } ChatClient.java import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket;
  • 10. import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.table.DefaultTableModel; public class ChatClient extends javax.swing.JFrame { /** * Creates new form ChatClient */ private ObjectInputStream input; private ObjectOutputStream output; private Socket socket; private String server, username; private int port; private List<String> clients; public ChatClient() { clients = new ArrayList(); initComponents(); } public boolean start() { try {
  • 11. socket = new Socket(server, port); } catch (Exception ec) { System.out.println("Error connectiong to server:" + ec); return false; } String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort(); System.out.println(msg); try { input = new ObjectInputStream(socket.getInputStream()); output = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException eIO) { System.out.println("Exception creating new Input/output Streams: " + eIO); return false; } new ChatClient.ListenFromServer().start(); try { output.writeObject("login~" + username + "~" + username + " sedang login...~server~n"); output.writeObject("list~" + username + "~" + username + " sedang login...~server~n"); } catch (IOException eIO) {
  • 12. System.out.println("Exception doing login : " + eIO); disconnect(); return false; } return true; } private void disconnect() { try { // TODO add your handling code here: output.writeObject("logout~" + username + "~" + username + " sudah logout...~Server~n"); } catch (IOException ex) { //Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } try { if (input != null) { input.close(); } } catch (Exception e) { } try { if (output != null) { output.close(); }
  • 13. } catch (Exception e) { } try { if (socket != null) { socket.close(); } } catch (Exception e) { } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); viewTextArea = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); clientTable = new javax.swing.JTable(); postTextField = new javax.swing.JTextField(); kirimButton = new javax.swing.JButton(); lbljpg = new javax.swing.JLabel(new ImageIcon("E:/rara.jpg"));
  • 14. jLabel2 = new javax.swing.JLabel(); serverTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); portTextField = new javax.swing.JTextField(); masukButton = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); usernameTextField = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE ); viewTextArea.setEditable(false); viewTextArea.setColumns(20); viewTextArea.setLineWrap(true); viewTextArea.setRows(5); viewTextArea.setFocusable(false); jScrollPane1.setViewportView(viewTextArea); jScrollPane2.setViewportView(clientTable); postTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { postTextFieldActionPerformed(evt); } }); kirimButton.setText("Kirim");
  • 15. kirimButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kirimButtonActionPerformed(evt); } }); jLabel2.setText("Server"); serverTextField.setText("10.17.0.0"); jLabel3.setText("Port"); portTextField.setText("9999"); masukButton.setText("Masuk"); masukButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { masukButtonActionPerformed(evt); } }); jLabel4.setText("Username"); usernameTextField.setText("Rara Ariesta");
  • 16. javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align ment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align ment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(postTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(kirimButton)) .addComponent(jScrollPane1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(lbljpg) .addComponent(jLabel2)
  • 17. .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(serverTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(usernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addComponent(masukButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap()
  • 18. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align ment.BASELINE) .addComponent(lbljpg) .addComponent(jLabel2) .addComponent(serverTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(portTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(masukButton) .addComponent(jLabel4) .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align ment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATE D) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Align ment.BASELINE)
  • 19. .addComponent(postTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(kirimButton)))) .addContainerGap()) ); pack(); }// </editor-fold> private void masukButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: this.server = serverTextField.getText(); this.port = new Integer(portTextField.getText()); this.username = usernameTextField.getText(); start(); } private void kirimButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: try { String message = "postText~" + username + "~" + postTextField.getText() + "~all~n"; output.writeObject(message); postTextField.setText(""); } catch (IOException ex) {
  • 20. Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } } private void postTextFieldActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: kirimButtonActionPerformed(evt); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/pla f.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break;
  • 21. } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log (java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log (java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log (java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ChatClient.class.getName()).log (java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new ChatClient().setVisible(true); } }); } // Variables declaration - do not modify
  • 22. private javax.swing.JTable clientTable; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton kirimButton; private javax.swing.JButton masukButton; private javax.swing.JTextField portTextField; private javax.swing.JTextField postTextField; private javax.swing.JTextField serverTextField; private javax.swing.JTextField usernameTextField; private javax.swing.JTextArea viewTextArea; private JLabel lbljpg ; // End of variables declaration class ListenFromServer extends Thread { @Override public void run() { while (true) { try { String msg = (String) input.readObject(); String res; String type = msg.split("~")[0]; String pengirim = msg.split("~")[1]; String text = msg.split("~")[2]; String kepada = msg.split("~")[3];
  • 23. switch (type) { case "recieveText": res = pengirim + ": " + text; viewTextArea.setText(viewTextArea.getText() + res + "n"); break; case "recievePrivateText": res = pengirim + ": " + text; if (kepada.equals(username)) { viewTextArea.setText(viewTextArea.getText() + res + "n"); } break; case "login": viewTextArea.setText(viewTextArea.getText() + pengirim + " sudah login..." + "n"); clients.add(pengirim); break; case "logout": viewTextArea.setText(viewTextArea.getText() + pengirim + " telah logout..." + "n"); clients.remove(pengirim); break; case "list": setTable(text); break; } } catch (IOException e) {
  • 24. System.out.println("Server has close the connection: " + e); break; } catch (ClassNotFoundException e2) { } } } private void setTable(String text) { int rows = text.split(":").length - 1; Object[][] data = new Object[rows][1]; for (int i = 0; i < rows; i++) { String t = text.split(":")[i]; data[i][0] = t; } String[] header = {"Clients"}; clientTable.setModel(new DefaultTableModel(data, header)); } } } Jika dijalankan maka tampilan akan seperti berikut: