mini-pms 35
1 minute read
Stateful 을 Stateless로 만들기
Server
클라이언트에게 응답하고 나면 연결을 끊는 방식으로 바꾼다.
.
.
.
private static void handleClient(Socket clientSocket) {
InetAddress address = clientSocket.getInetAddress();
System.out.printf("클라이언트(%s)가 연결되었습니다.\n",
address.getHostAddress());
try (Socket socket = clientSocket;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream())) {
// 한번만 통신하고 끊기 때문에 while 문으로 반복할 필요가 없다.
// 클라이언트가 보낸 요청을 읽는다.
String request = in.readLine();
// quit이 필요없기 때문에 삭제한다.
// if (request.equalsIgnoreCase("quit")) {
// out.println("안녕!");
// out.println();
// out.flush();
// break;
// } else
if (request.equalsIgnoreCase("stop")) {
stop = true;
out.println("서버를 종료하는 중입니다!");
out.println();
out.flush();
return;
}
Command command = (Command) context.get(request);
if (command != null) {
command.execute(out, in);
} else {
out.println("해당 명령을 처리할 수 없습니다!");
}
out.println();
out.flush();
} catch (Exception e) {
System.out.println("클라이언트와의 통신 오류!");
}
System.out.printf("클라이언트(%s)와의 연결을 끊었습니다.\n",
address.getHostAddress());
}
}
Client
서버에 연결할 때 한 번만 요청/응답하도록 변경한다.
public class ClientApp {
// host 와 port 변수를 준비한다.
static String host;
static int port;
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("프로그램 사용법");
System.out.println("java -cp ... ClientApp 서버주소 포트번호");
System.exit(0);
}
// host는 args의 0번째에 들어있고 port 번호는 args의 1번째에 들어있다.
host = args[0];
port = Integer.parseInt(args[1]);
// quit 일때 바로 클라이언트를 종료한다.
while (true) {
String input = Prompt.inputString("명령> ");
if (input.equalsIgnoreCase("quit")) {
break;
}
// request를 수행한다.
request(input);
// stop 일때 서버를 종료한다.
if (input.equalsIgnoreCase("stop")) {
break;
}
}
System.out.println("안녕!");
}
// request를 수행하는 메서드
private static void request(String message) {
// stop의 값을 false로 설정해 둔다.
boolean stop = false;
// socket을 통해 서버와 통신한다.
try (Socket socket = new Socket("localhost", 8888);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
// 메시지를 보낸다.
out.println(message);
out.flush();
// 서버의 리턴을 받는다.
receiveResponse(out, in);
// 만약 메시지가 stop 이라면 stop의 불린 값을 true로 바꾼다.
if (message.equalsIgnoreCase("stop")) {
stop = true;
}
} catch (Exception e) {
e.printStackTrace();
}
// 만약 stop이 참이라면 서버에 한 번 접속했다가 끊는다.
if (stop) {
try (Socket socket = new Socket(host, port)) {
} catch (Exception e) {
}
}
}
// 사용자로부터 값을 입력받는 파라미터를 만든다.
private static void receiveResponse(PrintWriter out, BufferedReader in) throws Exception {
while (true) {
String response = in.readLine();
if (response.length() == 0) {
break;
} else if (response.equals("!{}!")) {
// 사용자로부터 값을 입력받아서 서버에 보낸다.
out.println(Prompt.inputString(""));
out.flush();
} else {
System.out.println(response);
}
}
}
}