SimpleWebServer

Java-Spring/Java 2015. 4. 23. 11:13

package ch15;


import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;


public class SimpleWebServer {    // 같은 폴더내에 NewFile.html파일이 존재해야 작동함.

 // http://211.238.142.62:8800/NewFile.html

public static void main(String[] args) {

try {

ServerSocket ss = new ServerSocket(8800);

while (true) {

System.out.println("접속대기");

Socket sock = ss.accept();

System.out.println("새 쓰레드를 시작합니다");

HttpThread ht = new HttpThread(sock);

ht.start();

}

} catch (Exception ex) {

System.out.println(ex);

}


}


}


class HttpThread extends Thread {

private Socket sock = null;

BufferedReader br = null;

PrintWriter pw = null;


public HttpThread(Socket sock) {

this.sock = sock;


try {

br = new BufferedReader(

new InputStreamReader(sock.getInputStream()));

pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));

} catch (Exception ex) {

System.out.println(ex);

}

}


public void run() {

BufferedReader fbr = null;

try {

String line = br.readLine();

System.out.println("line : " + line);

int start = line.indexOf("/") + 1;

int end = line.lastIndexOf("HTTP") - 1;

String filename = line.substring(start, end);

System.out.println(filename);

if(filename.equals(""))

filename = "index.html";

System.out.println("사용자가 " + filename + "을 요청했습니다.");

fbr = new BufferedReader(new FileReader(filename));

String fline = null;

while ((fline = fbr.readLine()) != null) {

pw.println(fline);

pw.flush();

}

}

catch (Exception ex) {

System.out.println(ex);

}

finally {

try {

if(br != null)

br.close();

}

catch (Exception ex) {

}

try {

if(pw != null)

pw.close();

}

catch (Exception ex) {

}

}

}

}



Posted by 파란개발자
,