sebelum membuat class maka buatlah sebuah java project dengan cara klik File --> New --> Java Project , maka akan muncul tampilan seperti gambar dibawah ini :
setelah membuat java project maka kita akan membuat kelas, seperti gambar dibawah ini dengan cara klik File --> New --> Class maka akan muncul tampilan seperti gambar dibawah ini :
Kode program :
import java.io.*;
public class MyClient {
public static void main (String args[]) {
try {
//Socket client = new socket("133.0.0.1", 1234);
Socket client = new Socket (InetAddress.getLocalHost(), 1234);
InputStream clientIn = client.getInputStream();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
BufferedReader br = new BufferedReader(new InputStreamReader (clientIn));
BufferedReader stdIn = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Type a message for the server: ");
pw.println(stdIn.readLine());
System.out.println("server message: ");
System.out.println(br.readLine());
pw.close();
br.close();
client.close();
} catch (ConnectException ce) {System.out.println("Cannot connect to the server.");
} catch (IOException ie) { System.out.println("I/O Error.");
}
}
}
public class MyClient {
public static void main (String args[]) {
try {
//Socket client = new socket("133.0.0.1", 1234);
Socket client = new Socket (InetAddress.getLocalHost(), 1234);
InputStream clientIn = client.getInputStream();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
BufferedReader br = new BufferedReader(new InputStreamReader (clientIn));
BufferedReader stdIn = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Type a message for the server: ");
pw.println(stdIn.readLine());
System.out.println("server message: ");
System.out.println(br.readLine());
pw.close();
br.close();
client.close();
} catch (ConnectException ce) {System.out.println("Cannot connect to the server.");
} catch (IOException ie) { System.out.println("I/O Error.");
}
}
}
Screenshot kode program :
Screenshot Output :
yang akan muncul pertama adalah "Type a message for the server:"
setelah itu saya tulis "Fariz Gegewepe" yang warna biru muda
setelah itu "Server message"
dan output nya "Fariz Gegewepe" yang warna hitam
Sumber : JENI (Java Education Network Indonesia)
Tidak ada komentar:
Posting Komentar