SlideShare a Scribd company logo
Source Code Client
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tcp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author SHUBHAM
*/
public class Client {
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("127.0.0.1",5000);
BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
if ( s.equalsIgnoreCase("BYE") )
{
System.out.println("Connection ended by client");
break;
}
s=sin.readLine();
System.out.print("Server : "+s+"n");
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
Source Code Server
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package syarifchatting;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.Normalizer.Form;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JColorChooser;
import javax.swing.JOptionPane;
/**
* @author MhdSyarif
* Monday, 13 January 2014, 20 : 52 : 20 WIB
* Tugas III Matakulia Java2SE
* Mhd. Syarif | 49013075
* TKJMD - STEI - ITB
*/
public class Server extends javax.swing.JFrame implements Runnable{
int port=8080;
Socket client;
ServerSocket server;
BufferedReader Server_Reader, Client_Reader;
BufferedWriter Server_Writer, Client_Writer;
/**
* Creates new form Server
*/
//ServerSocket server=null;
// Socket client=null;
ExecutorService pool = null;
int clientcount=0;
// public static void main(String[] args) throws IOException {
// Server serverobj=new Server(5000);
// serverobj.startServer();
// }
Server(int port){
this.port=port;
pool = Executors.newFixedThreadPool(5);
}
public void Client() throws IOException
{
Socket sk=new Socket("127.0.0.1",5000);
BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
if ( s.equalsIgnoreCase("BYE") )
{
System.out.println("Connection ended by client");
break;
}
s=sin.readLine();
System.out.print("Server : "+s+"n");
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
public void startServer() throws IOException {
server=new ServerSocket(5000);
System.out.println("Server Booted");
System.out.println("Any client can stop the server by sending -1");
while(true)
{
client=server.accept();
clientcount++;
ServerThread runnable= new ServerThread(client,clientcount,this);
pool.execute(runnable);
}
}
private static class ServerThread implements Runnable {
Server server=null;
Socket client=null;
BufferedReader cin;
PrintStream cout;
Scanner sc=new Scanner(System.in);
int id;
String s;
ServerThread(Socket client, int count ,Server server ) throws
IOException {
this.client=client;
this.server=server;
this.id=count;
System.out.println("Connection "+id+"established with client
"+client);
cin=new BufferedReader(new
InputStreamReader(client.getInputStream()));
cout=new PrintStream(client.getOutputStream());
}
@Override
public void run() {
int x=1;
try{
while(true){
s=cin.readLine();
System. out.print("Client("+id+") :"+s+"n");
System.out.print("Server : ");
//s=stdin.readLine();
s=sc.nextLine();
if (s.equalsIgnoreCase("bye"))
{
cout.println("BYE");
x=0;
System.out.println("Connection ended by server");
break;
}
cout.println(s);
}
cin.close();
client.close();
cout.close();
if(x==0) {
System.out.println( "Server cleaning up." );
System.exit(0);
}
}
catch(IOException ex){
System.out.println("Error : "+ex);
}
}
}
public Server() {
super("www.mhdsyarif.com"); //SetTitle
initComponents();
//Menampilkan hasil ditengah window
java.awt.Dimension screenSize =
java.awt.Toolkit.getDefaultToolkit().getScreenSize();
java.awt.Dimension dialogSize = getSize();
setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-
dialogSize.height)/2);
}
//Pilihan ComboBox
private void getComboBox(){
if(ComboBox.getSelectedItem().equals("Server")){
ButtonOn.setText("On");
Username.setText("Server");
}else{
ButtonOn.setText("Connect");
Username.setText("Client");
}
}
//Koneksi client ke server
private void getClientConnec(){
try {
String ip = JOptionPane.showInputDialog(" Input IP Address");
client = new Socket(ip, port);
ComboBox.setEnabled(false);
ButtonOn.setText("Disconnect");
Server_Reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Server_Writer = new BufferedWriter (new
OutputStreamWriter(client.getOutputStream()));
} catch (UnknownHostException ex) {
System.out.println("Accept Failed");
System.exit(-1);
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null,
ex);
}
}
private void getReadConnec(){
try {
try {
try {
server = new ServerSocket(port);
this.setTitle("Please Wait");
} catch (IOException ex) {
System.out.println("Could not listen");
System.exit(-1);
}
client = server.accept();
this.setTitle("Connected" + client.getInetAddress());
} catch (IOException ex) {
System.out.println("Accept Failed");
System.exit(-1);
}
Server_Reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Server_Writer = new BufferedWriter(new
OutputStreamWriter(client.getOutputStream()));
} catch (IOException ex) {
System.out.println("Read Failed");
System.exit(-1);
}
}
private void getDisconnectedClient(){
try {
client.close();
Server_Reader.close();
Server_Writer.close();
ComboBox.setEnabled(true);
ButtonOn.setText("Connect");
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null,
ex);
}
}
private void getDisconnectedServer(){
try {
Server_Reader.close();
Server_Writer.close();
ButtonOn.setText("On");
this.setTitle("Disconected");
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null,
ex);
}
}
private void getButtonOn(){
if(ButtonOn.getText().equals("Connect"))
{
ButtonOn.setText("DIsconnect");
getClientConnec();
Thread thread1= new Thread(this);
Thread thread2= new Thread(this);
Thread thread3= new Thread(this);
Thread thread4= new Thread(this);
Thread thread5= new Thread(this);
Thread thread6= new Thread(this);
Thread thread7= new Thread(this);
Thread thread8= new Thread(this);
Thread thread9= new Thread(this);
Thread thread10= new Thread(this);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread10.start();
} else if(ComboBox.getSelectedItem().equals("Server")){
ButtonOn.setText("Off");
getReadConnec();
Thread thread1= new Thread(this);
Thread thread2= new Thread(this);
Thread thread3= new Thread(this);
Thread thread4= new Thread(this);
Thread thread5= new Thread(this);
Thread thread6= new Thread(this);
Thread thread7= new Thread(this);
Thread thread8= new Thread(this);
Thread thread9= new Thread(this);
Thread thread10= new Thread(this);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
thread9.start();
thread10.start();
}else if(ButtonOn.getText().equals("Disconnect")){
getDisconnectedClient();
}else if(ButtonOn.getText().equals("Off")){
getDisconnectedServer();
}
}
private void getSend(){
try {
Server_Writer.write(Username.getText()+ ": "
+TextChat.getText());
Server_Writer.newLine();
Server_Writer.flush();
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null,
ex);
}
ListChat.add(Username.getText()+ ": " +TextChat.getText());
//jClient.setText(Username.getText());
TextChat.setText("");
}
//Background color
public void getBackgroundColor(){
Color c = JColorChooser.showDialog(null,"Background
Color",jPanel.getBackground());
jPanel.setBackground(c);
}
//Konfirmasi keluar
public void getExit(){
int confirm =JOptionPane.showConfirmDialog(this,"Are you sure will
exit this application ?","Exit
Application",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION){
System.exit(0);
}
}
/**
* 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() {
Dialog = new javax.swing.JDialog();
ColorChooser = new javax.swing.JColorChooser();
jPanel = new javax.swing.JPanel();
ComboBox = new javax.swing.JComboBox();
ButtonOn = new javax.swing.JButton();
Send = new javax.swing.JToggleButton();
JUsername = new javax.swing.JLabel();
Username = new javax.swing.JTextField();
TextChat = new java.awt.TextArea();
ListChat = new java.awt.List();
jMenuBar1 = new javax.swing.JMenuBar();
File = new javax.swing.JMenu();
BackgroundColor = new javax.swing.JMenuItem();
Exit = new javax.swing.JMenuItem();
Help = new javax.swing.JMenu();
About = new javax.swing.JMenuItem();
javax.swing.GroupLayout DialogLayout = new
javax.swing.GroupLayout(Dialog.getContentPane());
Dialog.getContentPane().setLayout(DialogLayout);
DialogLayout.setHorizontalGroup(
DialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(DialogLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ColorChooser,
javax.swing.GroupLayout.PREFERRED_SIZE, 601,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
DialogLayout.setVerticalGroup(
DialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(DialogLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ColorChooser,
javax.swing.GroupLayout.PREFERRED_SIZE, 316,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setBackground(new java.awt.Color(204, 204, 204));
setResizable(false);
jPanel.setBackground(new java.awt.Color(204, 204, 204));
ComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"Server", "Client" }));
ComboBox.setToolTipText("");
ComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ComboBoxActionPerformed(evt);
}
});
ButtonOn.setText("On");
ButtonOn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonOnActionPerformed(evt);
}
});
Send.setText("SEND");
Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SendActionPerformed(evt);
}
});
JUsername.setText("Username");
Username.setText("Server");
javax.swing.GroupLayout jPanelLayout = new
javax.swing.GroupLayout(jPanel);
jPanel.setLayout(jPanelLayout);
jPanelLayout.setHorizontalGroup(
jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING)
.addGroup(jPanelLayout.createSequentialGroup()
.addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING, false)
.addGroup(jPanelLayout.createSequentialGroup()
.addComponent(JUsername)
.addGap(18, 18, 18)
.addComponent(Username,
javax.swing.GroupLayout.PREFERRED_SIZE, 237,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(ComboBox, 0,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(ButtonOn,
javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE))
.addComponent(ListChat,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(jPanelLayout.createSequentialGroup()
.addComponent(TextChat,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Send,
javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanelLayout.setVerticalGroup(
jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)
.addComponent(ComboBox,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ButtonOn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.
BASELINE)
.addComponent(JUsername)
.addComponent(Username,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ListChat,
javax.swing.GroupLayout.PREFERRED_SIZE, 179,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.
LEADING, false)
.addComponent(TextChat,
javax.swing.GroupLayout.PREFERRED_SIZE, 58,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Send, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
File.setText("File");
BackgroundColor.setText("Background Color");
BackgroundColor.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt) {
BackgroundColorActionPerformed(evt);
}
});
File.add(BackgroundColor);
Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEven
t.VK_W, java.awt.event.InputEvent.CTRL_MASK));
Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(evt);
}
});
File.add(Exit);
jMenuBar1.add(File);
Help.setText("Help");
About.setText("About");
About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutActionPerformed(evt);
}
});
Help.add(About);
jMenuBar1.add(Help);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void AboutActionPerformed(java.awt.event.ActionEvent evt) {
About a = new About();
a.setVisible(true);// TODO add your handling code here:
}
private void SendActionPerformed(java.awt.event.ActionEvent evt) {
getSend();// TODO add your handling code here:
}
private void ButtonOnActionPerformed(java.awt.event.ActionEvent evt) {
getButtonOn();
// TODO add your handling code here:
}
private void ComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
getComboBox();
}
private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
getExit();// TODO add your handling code here:
}
private void BackgroundColorActionPerformed(java.awt.event.ActionEvent
evt) {
getBackgroundColor();// TODO add your handling code here:
}
/**
* @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/plaf.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(Server.class.getName()).log(java.util.logg
ing.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg
ing.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg
ing.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg
ing.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem About;
private javax.swing.JMenuItem BackgroundColor;
private javax.swing.JButton ButtonOn;
private javax.swing.JColorChooser ColorChooser;
private javax.swing.JComboBox ComboBox;
private javax.swing.JDialog Dialog;
private javax.swing.JMenuItem Exit;
private javax.swing.JMenu File;
private javax.swing.JMenu Help;
private javax.swing.JLabel JUsername;
private java.awt.List ListChat;
private javax.swing.JToggleButton Send;
private java.awt.TextArea TextChat;
private javax.swing.JTextField Username;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel;
// End of variables declaration
@Override
public void run()
{
try {
ListChat.add(Server_Reader.readLine());
} catch (IOException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
Hasil
Pembahasan :
Source Code pada program ini hanya bisa dilakukan oleh server dan client, pada pesan dari
client dan server muncul pada layar server dan client.

More Related Content

What's hot

BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
MongoDB
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
IT Weekend
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Ryosuke Uchitate
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
CanSecWest
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Jersey framework
Jersey frameworkJersey framework
Jersey frameworkknight1128
 
The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202
Mahmoud Samir Fayed
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiowaspindy
 
Maximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digestMaximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digest
Pythian
 
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
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
guest2556de
 
Project in programming
Project in programmingProject in programming
Project in programming
sahashi11342091
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
Andrei Pangin
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
Thierry Wasylczenko
 

What's hot (18)

Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!Amazon Cognito使って認証したい?それならSpring Security使いましょう!
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 
Winform
WinformWinform
Winform
 
The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202The Ring programming language version 1.8 book - Part 54 of 202
The Ring programming language version 1.8 book - Part 54 of 202
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLi
 
Maximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digestMaximizing SQL Reviews and Tuning with pt-query-digest
Maximizing SQL Reviews and Tuning with pt-query-digest
 
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...
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
Project in programming
Project in programmingProject in programming
Project in programming
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 

Similar to Fia fabila

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Server1
Server1Server1
Server1
FahriIrawan3
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
Fahad Shaikh
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client servertrilestari08
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
Suman Astani
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
Niraj Bharambe
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
Rays Technologies
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
fadlihulopi
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
budbarber38650
 
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
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 

Similar to Fia fabila (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
java sockets
 java sockets java sockets
java sockets
 
Server1
Server1Server1
Server1
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
分散式系統
分散式系統分散式系統
分散式系統
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
Thread
ThreadThread
Thread
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
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
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 

Recently uploaded

Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 

Recently uploaded (20)

Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 

Fia fabila

  • 1. Source Code Client /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tcp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; /** * * @author SHUBHAM */ public class Client { public static void main(String args[]) throws Exception { Socket sk=new Socket("127.0.0.1",5000); BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream sout=new PrintStream(sk.getOutputStream()); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); String s; while ( true ) {
  • 2. System.out.print("Client : "); s=stdin.readLine(); sout.println(s); if ( s.equalsIgnoreCase("BYE") ) { System.out.println("Connection ended by client"); break; } s=sin.readLine(); System.out.print("Server : "+s+"n"); } sk.close(); sin.close(); sout.close(); stdin.close(); } } Source Code Server /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package syarifchatting; import java.awt.Color; import java.io.BufferedReader; import java.io.BufferedWriter;
  • 3. import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.Normalizer.Form; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JColorChooser; import javax.swing.JOptionPane; /** * @author MhdSyarif * Monday, 13 January 2014, 20 : 52 : 20 WIB * Tugas III Matakulia Java2SE * Mhd. Syarif | 49013075 * TKJMD - STEI - ITB */ public class Server extends javax.swing.JFrame implements Runnable{ int port=8080; Socket client; ServerSocket server; BufferedReader Server_Reader, Client_Reader; BufferedWriter Server_Writer, Client_Writer;
  • 4. /** * Creates new form Server */ //ServerSocket server=null; // Socket client=null; ExecutorService pool = null; int clientcount=0; // public static void main(String[] args) throws IOException { // Server serverobj=new Server(5000); // serverobj.startServer(); // } Server(int port){ this.port=port; pool = Executors.newFixedThreadPool(5); } public void Client() throws IOException { Socket sk=new Socket("127.0.0.1",5000); BufferedReader sin=new BufferedReader(new InputStreamReader(sk.getInputStream())); PrintStream sout=new PrintStream(sk.getOutputStream()); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); String s; while ( true ) { System.out.print("Client : ");
  • 5. s=stdin.readLine(); sout.println(s); if ( s.equalsIgnoreCase("BYE") ) { System.out.println("Connection ended by client"); break; } s=sin.readLine(); System.out.print("Server : "+s+"n"); } sk.close(); sin.close(); sout.close(); stdin.close(); } public void startServer() throws IOException { server=new ServerSocket(5000); System.out.println("Server Booted"); System.out.println("Any client can stop the server by sending -1"); while(true) { client=server.accept(); clientcount++; ServerThread runnable= new ServerThread(client,clientcount,this); pool.execute(runnable); }
  • 6. } private static class ServerThread implements Runnable { Server server=null; Socket client=null; BufferedReader cin; PrintStream cout; Scanner sc=new Scanner(System.in); int id; String s; ServerThread(Socket client, int count ,Server server ) throws IOException { this.client=client; this.server=server; this.id=count; System.out.println("Connection "+id+"established with client "+client); cin=new BufferedReader(new InputStreamReader(client.getInputStream())); cout=new PrintStream(client.getOutputStream()); } @Override public void run() { int x=1; try{ while(true){
  • 7. s=cin.readLine(); System. out.print("Client("+id+") :"+s+"n"); System.out.print("Server : "); //s=stdin.readLine(); s=sc.nextLine(); if (s.equalsIgnoreCase("bye")) { cout.println("BYE"); x=0; System.out.println("Connection ended by server"); break; } cout.println(s); } cin.close(); client.close(); cout.close(); if(x==0) { System.out.println( "Server cleaning up." ); System.exit(0); } } catch(IOException ex){ System.out.println("Error : "+ex); } }
  • 8. } public Server() { super("www.mhdsyarif.com"); //SetTitle initComponents(); //Menampilkan hasil ditengah window java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); java.awt.Dimension dialogSize = getSize(); setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height- dialogSize.height)/2); } //Pilihan ComboBox private void getComboBox(){ if(ComboBox.getSelectedItem().equals("Server")){ ButtonOn.setText("On"); Username.setText("Server"); }else{ ButtonOn.setText("Connect"); Username.setText("Client"); } } //Koneksi client ke server private void getClientConnec(){ try { String ip = JOptionPane.showInputDialog(" Input IP Address"); client = new Socket(ip, port); ComboBox.setEnabled(false); ButtonOn.setText("Disconnect");
  • 9. Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream())); Server_Writer = new BufferedWriter (new OutputStreamWriter(client.getOutputStream())); } catch (UnknownHostException ex) { System.out.println("Accept Failed"); System.exit(-1); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } } private void getReadConnec(){ try { try { try { server = new ServerSocket(port); this.setTitle("Please Wait"); } catch (IOException ex) { System.out.println("Could not listen"); System.exit(-1); } client = server.accept(); this.setTitle("Connected" + client.getInetAddress()); } catch (IOException ex) { System.out.println("Accept Failed"); System.exit(-1); } Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream())); Server_Writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
  • 10. } catch (IOException ex) { System.out.println("Read Failed"); System.exit(-1); } } private void getDisconnectedClient(){ try { client.close(); Server_Reader.close(); Server_Writer.close(); ComboBox.setEnabled(true); ButtonOn.setText("Connect"); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } } private void getDisconnectedServer(){ try { Server_Reader.close(); Server_Writer.close(); ButtonOn.setText("On"); this.setTitle("Disconected"); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } }
  • 11. private void getButtonOn(){ if(ButtonOn.getText().equals("Connect")) { ButtonOn.setText("DIsconnect"); getClientConnec(); Thread thread1= new Thread(this); Thread thread2= new Thread(this); Thread thread3= new Thread(this); Thread thread4= new Thread(this); Thread thread5= new Thread(this); Thread thread6= new Thread(this); Thread thread7= new Thread(this); Thread thread8= new Thread(this); Thread thread9= new Thread(this); Thread thread10= new Thread(this); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); thread7.start(); thread8.start(); thread9.start(); thread10.start(); } else if(ComboBox.getSelectedItem().equals("Server")){ ButtonOn.setText("Off"); getReadConnec(); Thread thread1= new Thread(this); Thread thread2= new Thread(this);
  • 12. Thread thread3= new Thread(this); Thread thread4= new Thread(this); Thread thread5= new Thread(this); Thread thread6= new Thread(this); Thread thread7= new Thread(this); Thread thread8= new Thread(this); Thread thread9= new Thread(this); Thread thread10= new Thread(this); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); thread7.start(); thread8.start(); thread9.start(); thread10.start(); }else if(ButtonOn.getText().equals("Disconnect")){ getDisconnectedClient(); }else if(ButtonOn.getText().equals("Off")){ getDisconnectedServer(); } } private void getSend(){ try { Server_Writer.write(Username.getText()+ ": " +TextChat.getText()); Server_Writer.newLine(); Server_Writer.flush();
  • 13. } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } ListChat.add(Username.getText()+ ": " +TextChat.getText()); //jClient.setText(Username.getText()); TextChat.setText(""); } //Background color public void getBackgroundColor(){ Color c = JColorChooser.showDialog(null,"Background Color",jPanel.getBackground()); jPanel.setBackground(c); } //Konfirmasi keluar public void getExit(){ int confirm =JOptionPane.showConfirmDialog(this,"Are you sure will exit this application ?","Exit Application",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); if (confirm == JOptionPane.YES_OPTION){ System.exit(0); } } /** * 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")
  • 14. // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { Dialog = new javax.swing.JDialog(); ColorChooser = new javax.swing.JColorChooser(); jPanel = new javax.swing.JPanel(); ComboBox = new javax.swing.JComboBox(); ButtonOn = new javax.swing.JButton(); Send = new javax.swing.JToggleButton(); JUsername = new javax.swing.JLabel(); Username = new javax.swing.JTextField(); TextChat = new java.awt.TextArea(); ListChat = new java.awt.List(); jMenuBar1 = new javax.swing.JMenuBar(); File = new javax.swing.JMenu(); BackgroundColor = new javax.swing.JMenuItem(); Exit = new javax.swing.JMenuItem(); Help = new javax.swing.JMenu(); About = new javax.swing.JMenuItem(); javax.swing.GroupLayout DialogLayout = new javax.swing.GroupLayout(Dialog.getContentPane()); Dialog.getContentPane().setLayout(DialogLayout); DialogLayout.setHorizontalGroup( DialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DialogLayout.createSequentialGroup() .addContainerGap() .addComponent(ColorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 601, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  • 15. ); DialogLayout.setVerticalGroup( DialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DialogLayout.createSequentialGroup() .addContainerGap() .addComponent(ColorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); setResizable(false); jPanel.setBackground(new java.awt.Color(204, 204, 204)); ComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Server", "Client" })); ComboBox.setToolTipText(""); ComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ComboBoxActionPerformed(evt); } }); ButtonOn.setText("On"); ButtonOn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonOnActionPerformed(evt);
  • 16. } }); Send.setText("SEND"); Send.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SendActionPerformed(evt); } }); JUsername.setText("Username"); Username.setText("Server"); javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel); jPanel.setLayout(jPanelLayout); jPanelLayout.setHorizontalGroup( jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment. LEADING) .addGroup(jPanelLayout.createSequentialGroup() .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment. LEADING, false) .addGroup(jPanelLayout.createSequentialGroup() .addComponent(JUsername) .addGap(18, 18, 18)
  • 17. .addComponent(Username, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(ComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(ButtonOn, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)) .addComponent(ListChat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanelLayout.createSequentialGroup() .addComponent(TextChat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Send, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jPanelLayout.setVerticalGroup( jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment. BASELINE) .addComponent(ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ButtonOn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment. BASELINE)
  • 18. .addComponent(JUsername) .addComponent(Username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ListChat, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment. LEADING, false) .addComponent(TextChat, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Send, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); File.setText("File"); BackgroundColor.setText("Background Color"); BackgroundColor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackgroundColorActionPerformed(evt); } }); File.add(BackgroundColor); Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEven t.VK_W, java.awt.event.InputEvent.CTRL_MASK));
  • 19. Exit.setText("Exit"); Exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExitActionPerformed(evt); } }); File.add(Exit); jMenuBar1.add(File); Help.setText("Help"); About.setText("About"); About.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AboutActionPerformed(evt); } }); Help.add(About); jMenuBar1.add(Help); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  • 20. ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> private void AboutActionPerformed(java.awt.event.ActionEvent evt) { About a = new About(); a.setVisible(true);// TODO add your handling code here: } private void SendActionPerformed(java.awt.event.ActionEvent evt) { getSend();// TODO add your handling code here: } private void ButtonOnActionPerformed(java.awt.event.ActionEvent evt) { getButtonOn(); // TODO add your handling code here: } private void ComboBoxActionPerformed(java.awt.event.ActionEvent evt) { getComboBox(); } private void ExitActionPerformed(java.awt.event.ActionEvent evt) { getExit();// TODO add your handling code here:
  • 21. } private void BackgroundColorActionPerformed(java.awt.event.ActionEvent evt) { getBackgroundColor();// TODO add your handling code here: } /** * @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/plaf.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(Server.class.getName()).log(java.util.logg ing.Level.SEVERE, null, ex); } catch (InstantiationException ex) {
  • 22. java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg ing.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg ing.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logg ing.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Server().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JMenuItem About; private javax.swing.JMenuItem BackgroundColor; private javax.swing.JButton ButtonOn; private javax.swing.JColorChooser ColorChooser; private javax.swing.JComboBox ComboBox; private javax.swing.JDialog Dialog; private javax.swing.JMenuItem Exit; private javax.swing.JMenu File; private javax.swing.JMenu Help; private javax.swing.JLabel JUsername; private java.awt.List ListChat;
  • 23. private javax.swing.JToggleButton Send; private java.awt.TextArea TextChat; private javax.swing.JTextField Username; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel; // End of variables declaration @Override public void run() { try { ListChat.add(Server_Reader.readLine()); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } } } Hasil
  • 24. Pembahasan : Source Code pada program ini hanya bisa dilakukan oleh server dan client, pada pesan dari client dan server muncul pada layar server dan client.