Contents
1. 요구사항반이중 통신을 사용한 HTTP 서버 프로토콜 제작 및 연습
1. 요구사항
- ch02 반이중 통신을 이용하라. ( 스레드 필요 없음 )
- 서버, 클라이언트 1대1 구조
- 서버 : HashMap 생성
- 4가지 프로토콜 (GET, POST, PUT, DELETE)
- 클라이언트 : 메시지를 아래와 같이 출력
// 1. GET
GET:name // 요청이 오면 HashMap에서 name 키의 값을 찾아서 클라이언트한테 전달
// 못 찾으면 (키 부재 or 값 부재) 404 응답
// 2. POST
POST:age/20 // 요청이 오면 HashMap에서 age의 키로 20을 저장한 뒤 클라이언트에게 OK 전달
// 3. PUT
PUT:name/홍길동 // 요청이 오면 HashMap에서 name의 값을 찾아 '홍길동'으로 수정 후 클라이언트에게 OK 전달
// 못 찾으면 404 응답
// 4. DELETE
DELETE:phone // 요청이 오면 HashMap의 phone 키와 그 값을 삭제
// 못 찾으면 404 응답
- Client
package ex20.ch02;
import java.io.*;
import java.net.Socket;
public class MyClient02 {
public static void main(String[] args) {
// 반이중 (Half-duplex) 통신 : 클라이언트
// localhost : loopback address (내 주소)
try {
// 소켓 연결
Socket socket = new Socket("localhost", 20000);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
// 키보드 입력
System.out.println("키보드 입력 대기중..");
String reqbody = in.readLine();
// 전송
out.write(reqbody);
out.write("\n");
out.flush();
// 응답 확인
String respbody = in2.readLine(); // Main Thread 입력 대기 : 자동 Interrupt
System.out.println(respbody);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
- Server
package ex20.ch02;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
public class MyServer02 {
public static void main(String[] args) {
// 반이중 (Half-duplex) 통신 : 서버
try {
ServerSocket ss = new ServerSocket(20000);
System.out.println("서버 소켓이 대기중입니다. 연결을 시도해주세요.");
// 서버 소켓이 연결을 인지하면 새 소켓 생성 (포트는 무작위)
Socket socket = ss.accept(); // 프로세스 멈춤 (대기 상태)
System.out.println("소켓이 연결되었습니다.");
HashMap<String, Object> map = new HashMap<>();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 메시지 계속 반복 : Main Thread
while (true) {
String reqbody = "";
reqbody = br.readLine();
// 1. parsing
String[] request = reqbody.split(":");
String protocol = request[0];
// 2. analyze protocol
String respbody = "";
if (protocol.equals("GET")) {
respbody = (String) map.get(request[1]);
if (respbody != null) {
bw.write(respbody);
bw.write("\n");
bw.flush();
} else {
respbody = "404 Not Found";
bw.write(respbody);
bw.write("\n");
bw.flush();
}
} else if (protocol.equals("POST")) {
String[] hash = request[1].split("/");
map.put(hash[0], hash[1]);
if (hash[0] != null && map.get(hash[0]) != null) {
respbody = "POST OK";
bw.write(respbody);
bw.write("\n");
bw.flush();
}
} else if (protocol.equals("PUT")) {
String[] hash = request[1].split("/");
map.replace(hash[0], hash[1]);
if (hash[0] != null && map.get(hash[0]) != null) {
respbody = "PUT OK";
bw.write(respbody);
bw.write("\n");
bw.flush();
}
} else if (protocol.equals("DELETE")) {
map.remove(request[1]);
respbody = "DELETE OK";
bw.write(respbody);
bw.write("\n");
bw.flush();
} else {
respbody = "404 Not Found";
bw.write(respbody);
bw.write("\n");
bw.flush();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
- Client

Share article