WebServer.java
package javawebserver;
import java.io.*;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer {
protected void start() {
ServerSocket s;
System.out.println("Webserver: Listening port 80");
try {
// buat server socket yang listen port 80
s = new ServerSocket(80);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Webserver: Waiting for connection..");
for (;;) {
try {
// infinite loop agar menunggu koneksi terus
// s.accept untuk membuka port 80 apakah ada koneksi
Socket remote = s.accept();
System.out.println("Webserver: Client Connected");
// membaca request dari browser
BufferedReader in = new BufferedReader(new InputStreamReader(
remote.getInputStream()));
// mengirim respond ke browser
PrintWriter out = new PrintWriter(remote.getOutputStream());
// membaca string request browser
String str = ".";
while (!str.equals(""))
str = in.readLine();
// spesifikasi file yang mau dibuka
File file = new File("jarkom.html");
int ch;
StringBuffer strContent = new StringBuffer("");
// baca filenya
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
// header HTTP
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// End of header HTTP
out.println("");
// data
out.println(strContent.toString());
out.flush();
// tutup koneksi dengan browser
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
}
JavaWebServer.java
// program ini hanya untuk menjalankan program intinya
package javawebserver;
public class JavaWebServer {
public static void main(String[] args) {
WebServer ws = new WebServer();
ws.start();
}
}
0 comments:
Post a Comment