/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ClientServer;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author manjava
*/
public class Server implements Runnable{
ServerSocket server;
Socket soc;
Server(){
try {
server = new ServerSocket(1818);
System.out.println("Server berjalan");
while(!server.isClosed()){
Thread s = new Thread(this);
s.sleep(1000);
s.start();
}
} catch (InterruptedException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void run() {
getSocket();
}
public Socket getSocket(){
if(soc==null){
try {
soc = server.accept();
System.out.println("Client masuk");
DataInputStream in = new DataInputStream(soc.getInputStream());
while(in!=null){
String names = in.readUTF();
System.out.println("Names :" + names);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
return soc;
}
public static void main(String[] args) {
new Server();
}
}
------Socket Client -----------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ClientServer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Client {
public static void main(String[] args){
DataOutputStream out = null;
Socket soc = null;
int i = 0;
String nama="suherman";
try {
soc= new Socket("localhost", 1818);
out = new DataOutputStream(soc.getOutputStream());
System.out.println("Client Sudah Connect");
while (out != null) {
out.writeUTF(nama + i);
System.out.println(nama + i);
Thread.sleep(1000);
if(i==10){
nama="Akang Herman";
}
i++;
}
} catch (InterruptedException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
try {
out.close();
soc.close();
} catch (IOException ex1) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
Tidak ada komentar:
Posting Komentar