Selasa, 16 April 2013

Webserver dengan Java

Berikut ini source code untuk membuka file yang telah kita tentukan :


public class Modul2 {

    /**
     * @param args the command line arguments
     */
   
    public static String readLine(InputStream is)throws IOException
    {
        String req = "";
        int c;
       
        while(true){
            c = is.read();
            req += (char)c;
           
            if((char)c == '\n')
                break;
        }
       
        return req;
    }
   
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            ServerSocket ss = new ServerSocket(6661);
           
           while(true)
           {
               Socket s = ss.accept();
               BufferedInputStream inp = new BufferedInputStream(s.getInputStream());
               BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
             
               int c, line;
               line = 0;
               String req = "";
               String path = "";
             
               while(!(req = readLine(inp)).equals("\r\n")){
                    System.out.print(req);

                    if(line == 0){
                        int start = 5;
                        for(int i=start; true ; i++){
                            if(req.charAt(i) != ' '){
                                path += req.charAt(i);
                            }
                            else break;
                        }
                    }

                    line++;
               }
               System.out.print(req);

                String body = "";

                String response = "";  // Untuk balasan dari server agar diterima oleh browser
                response = "HTTP/1.0 200 OK\r\n" +
                           "Content-Type: text/html\r\n" +
                           "Server: Bot\r\n" +
                           "\r\n";
               
                FileInputStream ifs = new FileInputStream("C:\\Users\\Ryan\\Documents\\index.html");  // Direktori file yang dimasukkan

                while((c = ifs.read()) != -1){  // Membaca baris text sampai nilai -1 atau NULL
                    response += (char) c;
                }

                out.write(response.getBytes());
                out.flush();


                inp.close();
                inp.close();
                s.close();
           }
           
           
        } catch (IOException ex) {
            Logger.getLogger(Modul2.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }
}


Tidak ada komentar:

Posting Komentar