SlideShare a Scribd company logo
LAPORAN TUGAS NETWORK PROGRAMMING
NAMA : RAHMAT HAMDANI
NIM: 201913002
Keterangan : Permasalahannyaterletakdisaatrun,chatyang dikirimolehclienttidakbisa
diketahui olehclientlain.Programtidakmendukunguntukmelakukanbroadcastantar client.
Server hanya bisa menerima satu client dan tidak menerima lebih dari satu client. Indikasi
permasalahannya terletak pada kekuatan jaringan yang tidak mendukung.
Source code
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.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.Normalizer.Form;
import java.util.Scanner;
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
*/
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);
getBackgroundColor();
}
//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);
// }
final int PORT = 8080;
try {
server = new ServerSocket(PORT);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE,
null, ex);
}
System.out.println("Server started...");
System.out.println("Wating for clients...");
while (true) {
try {
client = server.accept();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE,
null, ex);
}
Thread t = new Thread() {
public void run() {
try {
Server_Reader = new BufferedReader(new
InputStreamReader(client.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Server_Writer = new BufferedWriter (new
OutputStreamWriter(client.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
try (
PrintWriter out = new
PrintWriter(client.getOutputStream(), true);
Scanner in = new Scanner(client.getInputStream());
) {
while (in.hasNextLine()) {
String input = in.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Received radius from
client: " + input);
// double radius = Double.valueOf(input);
// double area = Math.PI* radius *radius ;
// out.println(area);
}
} catch (IOException e) { }
}
};
t.start();
}
}
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);
}
}
Ad

Recommended

Tdd iPhone For Dummies
Tdd iPhone For Dummies
Giordano Scalzo
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
yayaria
 
Exploit ie using scriptable active x controls version English
Exploit ie using scriptable active x controls version English
chen yuki
 
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
2013 syscan360 yuki_chen_syscan360_exploit your java native vulnerabilities o...
chen yuki
 
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Connect2017 DEV-1550 Why Java 8? Or, What's a Lambda?
Julian Robichaux
 
Networks lab
Networks lab
svijiiii
 
network programing lab file ,
network programing lab file ,
AAlha PaiKra
 
Sockets in nach0s
Sockets in nach0s
naniix21_3
 
Web
Web
googli
 
Celery
Celery
Òscar Vilaplana
 
Full Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
Salesforce Developers
 
Node.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Monitoring patterns for mitigating technical risk
Monitoring patterns for mitigating technical risk
Itai Frenkel
 
Unit Testing Express Middleware
Unit Testing Express Middleware
Morris Singer
 
node.js errors
node.js errors
LearningTech
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Ajax World Comet Talk
Ajax World Comet Talk
rajivmordani
 
Clean code via dependency injection + guice
Clean code via dependency injection + guice
Jordi Gerona
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 
Csphtp1 22
Csphtp1 22
HUST
 
Qunit Java script Un
Qunit Java script Un
akanksha arora
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
Testing in android
Testing in android
jtrindade
 
Server1
Server1
FahriIrawan3
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
assigemt calculater.docx
assigemt calculater.docx
zekfeker
 

More Related Content

What's hot (19)

Web
Web
googli
 
Celery
Celery
Òscar Vilaplana
 
Full Stack Unit Testing
Full Stack Unit Testing
GlobalLogic Ukraine
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
Salesforce Developers
 
Node.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Monitoring patterns for mitigating technical risk
Monitoring patterns for mitigating technical risk
Itai Frenkel
 
Unit Testing Express Middleware
Unit Testing Express Middleware
Morris Singer
 
node.js errors
node.js errors
LearningTech
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Ajax World Comet Talk
Ajax World Comet Talk
rajivmordani
 
Clean code via dependency injection + guice
Clean code via dependency injection + guice
Jordi Gerona
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 
Csphtp1 22
Csphtp1 22
HUST
 
Qunit Java script Un
Qunit Java script Un
akanksha arora
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
Testing in android
Testing in android
jtrindade
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
Salesforce Developers
 
Node.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
Monitoring patterns for mitigating technical risk
Monitoring patterns for mitigating technical risk
Itai Frenkel
 
Unit Testing Express Middleware
Unit Testing Express Middleware
Morris Singer
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Ajax World Comet Talk
Ajax World Comet Talk
rajivmordani
 
Clean code via dependency injection + guice
Clean code via dependency injection + guice
Jordi Gerona
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
DVClub
 
Csphtp1 22
Csphtp1 22
HUST
 
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
PHPcon Poland - Static Analysis of PHP Code – How the Heck did I write so man...
Rouven Weßling
 
Testing in android
Testing in android
jtrindade
 

Similar to Laporan tugas network programming (20)

Server1
Server1
FahriIrawan3
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
assigemt calculater.docx
assigemt calculater.docx
zekfeker
 
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.docx
hendriciraida
 
Write a java program to create a program that outputs to the command l.docx
Write a java program to create a program that outputs to the command l.docx
lez31palka
 
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.pdf
fashiongallery1
 
Laporan multiclient chatting client server
Laporan multiclient chatting client server
trilestari08
 
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-.docx
hendriciraida
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
fatoryoutlets
 
Networking Core Concept
Networking Core Concept
Rays Technologies
 
Client server part 12
Client server part 12
fadlihulopi
 
networks-lab-excercise3.pdf
networks-lab-excercise3.pdf
Jayaprasanna4
 
Network
Network
phanleson
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
Ghadeer AlHasan
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
RyanF2PLeev
 
java sockets
java sockets
Enam Ahmed Shahaz
 
Distributed Objects and JAVA
Distributed Objects and JAVA
elliando dias
 
Laporan multi client
Laporan multi client
ichsanbarokah
 
Socket Programming
Socket Programming
Sivadon Chaisiri
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
assigemt calculater.docx
assigemt calculater.docx
zekfeker
 
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.docx
hendriciraida
 
Write a java program to create a program that outputs to the command l.docx
Write a java program to create a program that outputs to the command l.docx
lez31palka
 
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.pdf
fashiongallery1
 
Laporan multiclient chatting client server
Laporan multiclient chatting client server
trilestari08
 
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-.docx
hendriciraida
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
fatoryoutlets
 
Client server part 12
Client server part 12
fadlihulopi
 
networks-lab-excercise3.pdf
networks-lab-excercise3.pdf
Jayaprasanna4
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
Ghadeer AlHasan
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
RyanF2PLeev
 
Distributed Objects and JAVA
Distributed Objects and JAVA
elliando dias
 
Laporan multi client
Laporan multi client
ichsanbarokah
 
Ad

Recently uploaded (20)

How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
Ad

Laporan tugas network programming

  • 1. LAPORAN TUGAS NETWORK PROGRAMMING NAMA : RAHMAT HAMDANI NIM: 201913002 Keterangan : Permasalahannyaterletakdisaatrun,chatyang dikirimolehclienttidakbisa diketahui olehclientlain.Programtidakmendukunguntukmelakukanbroadcastantar client.
  • 2. Server hanya bisa menerima satu client dan tidak menerima lebih dari satu client. Indikasi permasalahannya terletak pada kekuatan jaringan yang tidak mendukung. Source code 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.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.Normalizer.Form; import java.util.Scanner; 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 */
  • 3. 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 */ 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); getBackgroundColor(); } //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) {
  • 4. // 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); // } final int PORT = 8080; try { server = new ServerSocket(PORT); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Server started..."); System.out.println("Wating for clients..."); while (true) { try { client = server.accept(); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } Thread t = new Thread() { public void run() { try { Server_Reader = new BufferedReader(new InputStreamReader(client.getInputStream())); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } try { Server_Writer = new BufferedWriter (new OutputStreamWriter(client.getOutputStream())); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } try ( PrintWriter out = new PrintWriter(client.getOutputStream(), true); Scanner in = new Scanner(client.getInputStream()); ) {
  • 5. while (in.hasNextLine()) { String input = in.nextLine(); if (input.equalsIgnoreCase("exit")) { break; } System.out.println("Received radius from client: " + input); // double radius = Double.valueOf(input); // double area = Math.PI* radius *radius ; // out.println(area); } } catch (IOException e) { } } }; t.start(); } } 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();
  • 6. 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
  • 7. 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); } }