SlideShare a Scribd company logo
1 of 8
Pemrograman Jaringan Komputer
Chatting dengan Beberapa PC/Laptop
Program ini digunakan untuk chating dengan beberapa PC/Laptop. Berikut adalah
listing codenya.
MultiThreadChatServer.java
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
/*
* chat server yang mengantar pesan publik dan private.
*/
public class MultiThreadChatServer {
// server socket.
private static ServerSocket serverSocket = null;
// client socket.
private static Socket clientSocket = null;
// chat server dapat menerima sampai maxClientsCount pada koneksi
client.
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new
clientThread[maxClientsCount];
public static void main(String args[]) {
// default port number.
int portNumber = 2222;
if (args.length < 1) {
System.out
.println("Usage: java MultiThreadChatServer <portNumber>n"
+ "Now using port number=" + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
/*
* buka server socket pada portNumber (default 2222). catatan:kita
tidak da
* pat memilih port dibawah 1023 jika kita bukan administrator
(root).
*/
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
/*
* buat client socket untuk setiap koneksi dan sesuaikan dengan
thread
* client baru.
*/
while (true) {
try {
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket,
threads)).start();
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new
PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
/*
* Thread chat client . thread client ini membuka input dan output
* streams untuk hubungan client, menanyakan nama
client,menginformasikan semua
* client yang terhubung ke server bahwa ada client baru yang
terhubung ke da-
* lam chatroom, selama data diterima, data di kembalikan ke semua
* client. saat client meninggalkan chatroom thread ini juga
menginformasikan
* pada client lainnya.
*/
class clientThread extends Thread {
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
/*
* membuat input dan output streams untuk client.
*/
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
String name = is.readLine().trim();
os.println("Hello " + name
+ " to our chat room.nTo leave enter /quit in a new line");
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** A new user " + name
+ " entered the chat room !!! ***");
}
}
while (true) {
String line = is.readLine();
if (line.startsWith("/quit")) {
break;
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null) {
threads[i].os.println("<" + name + "&gr; " + line);
}
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** The user " + name
+ " is leaving the chat room !!! ***");
}
}
os.println("*** Bye " + name + " ***");
/*
* buat variabel thread terakhir menjadi null agar client baru
* dapat diterima oleh server.
*/
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
/*
* tutup output stream, tutup input stream, tutup socket.
*/
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
}
}
MultiThreadChatClient.java
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MultiThreadChatClient implements Runnable {
// client socket
private static Socket clientSocket = null;
// output stream
private static PrintStream os = null;
// input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) {
// default port.
int portNumber = 2222;
// default host.
String host = "10.17.193.86";
if (args.length < 2) {
System.out
.println("Usage: java MultiThreadChatClient <host>
<portNumber>n"
+ "Now using host=" + host + ", portNumber=" +
portNumber);
} else {
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
/*
* Buka sebuah socket pada host dan port. Buka input dan output
streams.
*/
try {
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new
InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the
host "
+ host);
}
/*
* Jika semua telah diinisialisasi lalu kita ingin menulis data
pada socket yang kita buka pada koneksi port number.
*/
if (clientSocket != null && os != null && is != null) {
try {
/* Buat sebuah thread untuk membaca dari server. */
new Thread(new MultiThreadChatClient()).start();
while (!closed) {
os.println(inputLine.readLine().trim());
}
/*
* tutup output stream, tutup input stream, tutup socket.
*/
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
/*
* buat sebuah thread untuk membaca dari server.
*/
public void run() {
/*
* tetap membaca dari socket sampai kita menerima "Bye" dari
* server. setelah diterima maka break.
*/
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
Pertama, running program MultiThreadChatServer.java, kemudian akan muncul
tampilan seperti ini.
Kemudian running program MultiThreadChatClient.java, kemudian pada tampilan
MultiThreadChatClient akan muncul tampilan seperti ini.
Jika sudah terkoneksi, maka anda bisa langsung chat dengan PC/Laptop yang berbeda.

More Related Content

What's hot

MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
yoyomay93
 
Multi client
Multi clientMulti client
Multi client
Aisy 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
 
Multi client
Multi clientMulti client
Multi client
ganteng8
 

What's hot (20)

Book
BookBook
Book
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClient
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
 
Whispered secrets
Whispered secretsWhispered secrets
Whispered secrets
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambar
 
Multi client
Multi clientMulti client
Multi client
 
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
 
Fidl analysis
Fidl analysisFidl analysis
Fidl analysis
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
MQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker ExamplesMQTT and Java - Client and Broker Examples
MQTT and Java - Client and Broker Examples
 
Building Java and Android apps on the blockchain
Building Java and Android apps on the blockchain Building Java and Android apps on the blockchain
Building Java and Android apps on the blockchain
 
Creating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and softwareCreating an Arduino Web Server from scratch hardware and software
Creating an Arduino Web Server from scratch hardware and software
 
Winform
WinformWinform
Winform
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Web3j 2.0 Update
Web3j 2.0 UpdateWeb3j 2.0 Update
Web3j 2.0 Update
 
Socket.io v.0.8.3
Socket.io v.0.8.3Socket.io v.0.8.3
Socket.io v.0.8.3
 
Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)Laporan multiclient chatting berbasis grafis (gambar)
Laporan multiclient chatting berbasis grafis (gambar)
 
Php engine
Php enginePhp engine
Php engine
 
Multi client
Multi clientMulti client
Multi client
 

Viewers also liked (17)

Tugas 1
Tugas 1Tugas 1
Tugas 1
 
Waxraninaka pdf
Waxraninaka pdfWaxraninaka pdf
Waxraninaka pdf
 
instalar google drive en windows
instalar google drive en windowsinstalar google drive en windows
instalar google drive en windows
 
This is What Matters
This is What MattersThis is What Matters
This is What Matters
 
Mosa book es-de
Mosa book es-deMosa book es-de
Mosa book es-de
 
The ABC of IoT
The ABC of IoTThe ABC of IoT
The ABC of IoT
 
Capps vacation
Capps vacationCapps vacation
Capps vacation
 
Muaz
MuazMuaz
Muaz
 
Facebook Dilemma
Facebook DilemmaFacebook Dilemma
Facebook Dilemma
 
Info server dan info client
Info server dan info clientInfo server dan info client
Info server dan info client
 
Browsing (1)
Browsing (1)Browsing (1)
Browsing (1)
 
Asap methodology
Asap methodologyAsap methodology
Asap methodology
 
Sinha_WhitePaper
Sinha_WhitePaperSinha_WhitePaper
Sinha_WhitePaper
 
Sustainable transport
Sustainable transportSustainable transport
Sustainable transport
 
Apostilaadministracao aplicada-a-seguranca-no-trabalho-150317074308-conversio...
Apostilaadministracao aplicada-a-seguranca-no-trabalho-150317074308-conversio...Apostilaadministracao aplicada-a-seguranca-no-trabalho-150317074308-conversio...
Apostilaadministracao aplicada-a-seguranca-no-trabalho-150317074308-conversio...
 
Herbology review HiH
Herbology review HiHHerbology review HiH
Herbology review HiH
 
Program sms menggunakan java ria
Program sms menggunakan java riaProgram sms menggunakan java ria
Program sms menggunakan java ria
 

Similar to Chatting dengan beberapa pc laptop

Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
ichsanbarokah
 
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
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
Sasi Kala
 
16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming Servers
Adil Jafri
 
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
 

Similar to Chatting dengan beberapa pc laptop (20)

Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
 
java sockets
 java sockets java sockets
java sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Network
NetworkNetwork
Network
 
Os 2
Os 2Os 2
Os 2
 
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
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
 
A.java
A.javaA.java
A.java
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 
Network programming1
Network programming1Network programming1
Network programming1
 
Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in program
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming Servers
 
Networking Core Concept
Networking Core ConceptNetworking Core Concept
Networking Core Concept
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
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
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Chatting dengan beberapa pc laptop

  • 1. Pemrograman Jaringan Komputer Chatting dengan Beberapa PC/Laptop Program ini digunakan untuk chating dengan beberapa PC/Laptop. Berikut adalah listing codenya. MultiThreadChatServer.java import java.io.DataInputStream; import java.io.PrintStream; import java.io.IOException; import java.net.Socket; import java.net.ServerSocket; /* * chat server yang mengantar pesan publik dan private. */ public class MultiThreadChatServer { // server socket. private static ServerSocket serverSocket = null; // client socket. private static Socket clientSocket = null; // chat server dapat menerima sampai maxClientsCount pada koneksi client. private static final int maxClientsCount = 10; private static final clientThread[] threads = new clientThread[maxClientsCount]; public static void main(String args[]) { // default port number. int portNumber = 2222; if (args.length < 1) { System.out .println("Usage: java MultiThreadChatServer <portNumber>n" + "Now using port number=" + portNumber); } else { portNumber = Integer.valueOf(args[0]).intValue(); }
  • 2. /* * buka server socket pada portNumber (default 2222). catatan:kita tidak da * pat memilih port dibawah 1023 jika kita bukan administrator (root). */ try { serverSocket = new ServerSocket(portNumber); } catch (IOException e) { System.out.println(e); } /* * buat client socket untuk setiap koneksi dan sesuaikan dengan thread * client baru. */ while (true) { try { clientSocket = serverSocket.accept(); int i = 0; for (i = 0; i < maxClientsCount; i++) { if (threads[i] == null) { (threads[i] = new clientThread(clientSocket, threads)).start(); break; } } if (i == maxClientsCount) { PrintStream os = new PrintStream(clientSocket.getOutputStream()); os.println("Server too busy. Try later."); os.close(); clientSocket.close(); } } catch (IOException e) { System.out.println(e); } } } }
  • 3. /* * Thread chat client . thread client ini membuka input dan output * streams untuk hubungan client, menanyakan nama client,menginformasikan semua * client yang terhubung ke server bahwa ada client baru yang terhubung ke da- * lam chatroom, selama data diterima, data di kembalikan ke semua * client. saat client meninggalkan chatroom thread ini juga menginformasikan * pada client lainnya. */ class clientThread extends Thread { private DataInputStream is = null; private PrintStream os = null; private Socket clientSocket = null; private final clientThread[] threads; private int maxClientsCount; public clientThread(Socket clientSocket, clientThread[] threads) { this.clientSocket = clientSocket; this.threads = threads; maxClientsCount = threads.length; } public void run() { int maxClientsCount = this.maxClientsCount; clientThread[] threads = this.threads; try { /* * membuat input dan output streams untuk client. */ is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); os.println("Enter your name."); String name = is.readLine().trim(); os.println("Hello " + name + " to our chat room.nTo leave enter /quit in a new line"); for (int i = 0; i < maxClientsCount; i++) {
  • 4. if (threads[i] != null && threads[i] != this) { threads[i].os.println("*** A new user " + name + " entered the chat room !!! ***"); } } while (true) { String line = is.readLine(); if (line.startsWith("/quit")) { break; } for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null) { threads[i].os.println("<" + name + "&gr; " + line); } } } for (int i = 0; i < maxClientsCount; i++) { if (threads[i] != null && threads[i] != this) { threads[i].os.println("*** The user " + name + " is leaving the chat room !!! ***"); } } os.println("*** Bye " + name + " ***"); /* * buat variabel thread terakhir menjadi null agar client baru * dapat diterima oleh server. */ for (int i = 0; i < maxClientsCount; i++) { if (threads[i] == this) { threads[i] = null; } } /* * tutup output stream, tutup input stream, tutup socket. */ is.close(); os.close(); clientSocket.close(); } catch (IOException e) {
  • 5. } } } MultiThreadChatClient.java import java.io.DataInputStream; import java.io.PrintStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class MultiThreadChatClient implements Runnable { // client socket private static Socket clientSocket = null; // output stream private static PrintStream os = null; // input stream private static DataInputStream is = null; private static BufferedReader inputLine = null; private static boolean closed = false; public static void main(String[] args) { // default port. int portNumber = 2222; // default host. String host = "10.17.193.86"; if (args.length < 2) { System.out .println("Usage: java MultiThreadChatClient <host> <portNumber>n" + "Now using host=" + host + ", portNumber=" + portNumber); } else { host = args[0];
  • 6. portNumber = Integer.valueOf(args[1]).intValue(); } /* * Buka sebuah socket pada host dan port. Buka input dan output streams. */ try { clientSocket = new Socket(host, portNumber); inputLine = new BufferedReader(new InputStreamReader(System.in)); os = new PrintStream(clientSocket.getOutputStream()); is = new DataInputStream(clientSocket.getInputStream()); } catch (UnknownHostException e) { System.err.println("Don't know about host " + host); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to the host " + host); } /* * Jika semua telah diinisialisasi lalu kita ingin menulis data pada socket yang kita buka pada koneksi port number. */ if (clientSocket != null && os != null && is != null) { try { /* Buat sebuah thread untuk membaca dari server. */ new Thread(new MultiThreadChatClient()).start(); while (!closed) { os.println(inputLine.readLine().trim()); } /* * tutup output stream, tutup input stream, tutup socket. */ os.close(); is.close(); clientSocket.close(); } catch (IOException e) { System.err.println("IOException: " + e);
  • 7. } } } /* * buat sebuah thread untuk membaca dari server. */ public void run() { /* * tetap membaca dari socket sampai kita menerima "Bye" dari * server. setelah diterima maka break. */ String responseLine; try { while ((responseLine = is.readLine()) != null) { System.out.println(responseLine); if (responseLine.indexOf("*** Bye") != -1) break; } closed = true; } catch (IOException e) { System.err.println("IOException: " + e); } } } Pertama, running program MultiThreadChatServer.java, kemudian akan muncul tampilan seperti ini. Kemudian running program MultiThreadChatClient.java, kemudian pada tampilan MultiThreadChatClient akan muncul tampilan seperti ini.
  • 8. Jika sudah terkoneksi, maka anda bisa langsung chat dengan PC/Laptop yang berbeda.