메뉴 건너뛰기

infra

[java] 서버-클라이언트 모델 소스 주석

박영식2008.12.07 21:24조회 수 4756댓글 0

    • 글자 크기

<HttpRequest.java>


/**


* Chapter 2.


*/



import java.io.* ;


import java.net.* ;


//두개의 class를 제공 합니다. Socket, ServerSocket



import java.util.* ;



final class HttpRequest implements Runnable {


final static String CRLF = "rn";


Socket socket;



// Constructor


public HttpRequest(Socket socket) throws Exception {


this.socket = socket;


}



// Implement the run() method of the Runnable interface.


public void run() {


try {


processRequest();


} catch (Exception e) {


System.out.println(e);


}


}



private void processRequest() throws Exception {


//소켓으로 작업했을때는 반드시 소켓을 닫아야 합니다.


//소켓에 의하여 입출력 스트림을 닫을수 있기때문에



InputStream is = socket.getInputStream();


DataOutputStream os = new DataOutputStream(socket.getOutputStream());


//소켓에서 출력



BufferedReader br = new BufferedReader(new InputStreamReader(is));


//입력된 소켓의 정보를 읽습니다.



String requestLine = br.readLine();


//입력된 소켓의 정보 한줄




// Extract the filename from the request line.


StringTokenizer tokens = new StringTokenizer(requestLine);


//출력 소켓의 입력된 정보 한줄



tokens.nextToken(); // skip over the method, which should be "GET"


String fileName = tokens.nextToken();



// Prepend a "." so that file request is within the current directory.


fileName = "." + fileName ;



// Open the requested file.


FileInputStream fis = null ;


boolean fileExists = true ;


try {


fis = new FileInputStream(fileName);


} catch (FileNotFoundException e) {


fileExists = false ;


}



// Debug info for private use


System.out.println("Incoming!!!");


System.out.println(requestLine);


String headerLine = null;


while ((headerLine = br.readLine()).length() != 0) {


System.out.println(headerLine);


}



// Construct the response message.


String statusLine = null;


String contentTypeLine = null;


String entityBody = null;


if (fileExists) {


statusLine = "HTTP/1.0 200 OK" + CRLF; // 요청 파일이 존재하면 200 신호


contentTypeLine = "Content-Type: " +


contentType(fileName) + CRLF;


} else {


statusLine = "HTTP/1.0 404 Not Found" + CRLF; // 요청 파일이 존재하지 않으면 404 신호


contentTypeLine = "Content-Type: text/html" + CRLF;


entityBody = "<HTML>" +


"<HEAD><TITLE>Not Found</TITLE></HEAD>" +


"<BODY>Not Found</BODY></HTML>";


}


// Send the status line.


os.writeBytes(statusLine);



// Send the content type line.


os.writeBytes(contentTypeLine);



// Send a blank line to indicate the end of the header lines.


os.writeBytes(CRLF);



// Send the entity body.


if (fileExists) {


sendBytes(fis, os);


fis.close();


} else {


os.writeBytes(entityBody) ;


}



os.close();//출력 스트립을 닫아줍니다.


br.close(); //버퍼를 닫아줍니다.


socket.close();//소켓을 닫아줍니다.



}



private static void sendBytes(FileInputStream fis,


OutputStream os) throws Exception {


// Construct a 1K buffer to hold bytes on their way to the socket.


byte[] buffer = new byte[1024]; // 버퍼를 1024byte씩 배열로 지정하여, 전송


int bytes = 0;



// Copy requested file into the socket's output stream.


while ((bytes = fis.read(buffer)) != -1) {


os.write(buffer, 0, bytes);


}


}



private static String contentType(String fileName) { // html과 ram(real player 타입에 대해 확장명 지정


if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {


return "text/html";


}


if(fileName.endsWith(".ram") || fileName.endsWith(".ra")) {


return "audio/x-pn-realaudio";


}


return "application/octet-stream" ;


}


}



<WebServer.java>


import java.net.* ;


//두개의 class를 제공 합니다. Socket, ServerSocket



public final class WebServer {


public static void main(String argv[]) throws Exception {


int port = 0; // port 변수 초기화


// Get the port number from the command line.


if(argv.length == 0) {


port = 80; // 수신 대기 포트를 기본 80으로 지정


} else if(argv.length == 1) {


port = (new Integer(argv[0])).intValue();


} else {


System.out.println("Usage : WebServer [PortNum]"); // 사용법 알림


return;


}



// Establish the listen socket.


ServerSocket socket = new ServerSocket(port);



// Process HTTP service requests in an infinite loop.


while (true) {


// Listen for a TCP connection request.


Socket connection = socket.accept();


//client로 부터 들어오는 connection을 받는다.



// Construct an object to process the HTTP request message.


HttpRequest request = new HttpRequest(connection);


//create instance of HttpRequest


//object 생성



// Create a new thread to process the request.


Thread thread = new Thread(request);


//쓰레드 생성



// Start the thread.


thread.start(); // 쓰레드 시작


}


}


}

박영식 (비회원)
    • 글자 크기
[아이폰] 사파리에서 meta 태그를 이용해 주소창, 버튼 가리기 + slider (by suritam9) [tomcat] classpath와 외부 사이트 엑세스 허용 in 우분투 (by 박영식)

댓글 달기

박영식
2011.04.29 조회 6045
박영식
2009.08.01 조회 5409
lispro06
2016.03.30 조회 4588
첨부 (0)
위로