import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Server {
public static void main(String[] args){
int port = 6666;
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Menunggu pengguna atau admin");
Socket socket = ss.accept();
System.out.println("Terjadi koneksi\n");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
String line = null;
while(true) {
line = in.readUTF();
if ("saya pengguna".equals(line))
{
line = "SELAMAT DATANG PENGGUNA";
System.out.println("koneksi dengan pengguna\n");
}
if ("saya admin".equals(line))
{
line = "SELAMAT DATANG ADMIN";
System.out.println("koneksi dengan admin\n");
}
out.writeUTF(line);
out.flush();
System.out.println();
}
}
catch(Exception x) {
x.printStackTrace();
}
}
}
Code dari sisi Client :
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Client {
public static void main(String[] args){
int serverPort = 6666;
String address = "127.0.0.1";given here means "the same computer as the client".
try {
InetAddress ipAddress = InetAddress.getByName(address);
Socket socket = new Socket(ipAddress, serverPort);
System.out.println("Tersambung dengan server\n");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true) {
System.out.print("\nClient : ");
line = keyboard.readLine();
out.writeUTF(line);
out.flush();
line = in.readUTF();
System.out.print("Server : " + line);
}
}
catch(Exception x) {
x.printStackTrace();
}
}
}
Tidak ada komentar:
Posting Komentar