Tuesday, November 30, 2010

Belajar Jaringan pada Java

saya sedang belajar jaringan pada java,
pada Jaringan java ada yang akan menjadi server, dan ada yang akan menjadi client.

ini source code untuk server :

package server;
import java.net.*;
import java.io.*;
public class servertyang {
    public static void main(String [] args) {
        ServerSocket server = null;
        Socket client;
        try {
            server = new ServerSocket(31);
            //1234 is an unused port number
        } catch (IOException ie) {
            System.out.println("Cannot open socket.");
            System.exit(1);
        }
        while(true) {
            try {
                client = server.accept();
                OutputStream clientOut = client.getOutputStream();
                PrintWriter pw = new PrintWriter(clientOut, true);
                InputStream clientIn = client.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
               
                String in = br.readLine();
                if(in.equals("Halo"))pw.println("apa kabar?");
                if(in.equals("Boleh Kenalan?")) pw.println("Boleh donk, aku tyang, kamu siapa?");
                if(in.equals("Saya Jawi Salam kenal.")) pw.println("salam kenal juga.");
               
               
            } catch (IOException ie) {
            }
        }
    }
}


dan yang ini untuk client :

package client;
import java.io.*;
import java.net.*;
public class clienttyang {
    public static void main(String args[]) {
        try {//Socket client = new Socket("133.0.0.1", 1234);
            Socket client = new Socket("192.168.78.136",31);
            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.");{
           
        }
    }
}
}


kedua source code di atas merupakan source code sederhana untuk jaringan pada java. kata dosen saya, source code itu bisa dikembangkan menjadi aplikasi chat.