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

swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientShinya Mochida
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machinejulien pauli
 
MultiClient chatting berbasis gambar
MultiClient chatting berbasis gambarMultiClient chatting berbasis gambar
MultiClient chatting berbasis gambaryoyomay93
 
Multi client
Multi clientMulti client
Multi clientAisy Cuyy
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transferVictor Cherkassky
 
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 ExamplesMicha Kops
 
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 Conor Svensson
 
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 softwareJustin Mclean
 
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 clientganteng8
 

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

This is What Matters
This is What MattersThis is What Matters
This is What Mattersamizen
 
The ABC of IoT
The ABC of IoTThe ABC of IoT
The ABC of IoTcprojector
 
Capps vacation
Capps vacationCapps vacation
Capps vacationmtcapps
 
Info server dan info client
Info server dan info clientInfo server dan info client
Info server dan info clientyayaria
 
Browsing (1)
Browsing (1)Browsing (1)
Browsing (1)yayaria
 
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...helderoliveira85
 
Herbology review HiH
Herbology review HiHHerbology review HiH
Herbology review HiHlouise searle
 
Program sms menggunakan java ria
Program sms menggunakan java riaProgram sms menggunakan java ria
Program sms menggunakan java riayayaria
 

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 clientichsanbarokah
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 
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.docxhendriciraida
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)Ghadeer AlHasan
 
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 programgovindjha339843
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 
16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming ServersAdil Jafri
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In JavaAnkur Agrawal
 
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-.docxhendriciraida
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 

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

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 

Recently uploaded (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 

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.