본문 바로가기

Project

데이터 관리 서버 만들기 - 3) 사용자가 입력한 명령처리

728x90

client 버전

1단계 - 사용자가 입력한 명령을 서버에 전송한다.

  • .util.Prompt 가져오기

이전 프로젝트에서 가져온다.

  • .ClientApp 변경

Prompt 를 사용하여 사용자 입력을 처리한다.

 

public class ClientApp {

  public static void main(String[] args) throws Exception {
    System.out.println("[PMS 클라이언트]");

    System.out.println("1) 서버와 연결 중");
    Socket socket = new Socket("127.0.0.1", 8888); // 서버와 접속이 이루어지면 리턴한다.

    System.out.println("2) 서버와 연결되었음");

    PrintWriter out = new PrintWriter(socket.getOutputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    while (true) {
      String input = Prompt.inputString("명령> ");
      out.println(input);
      out.flush();

      String result = in.readLine();  // 서버에서 한 줄의 문자열을 보낼 때까지 기다린다.
      System.out.println(">>> " + result);

      if (input.equalsIgnoreCase("quit")) {
        break;
      }
    }

    System.out.println("3) 서버와의 접속을 끊음");
    out.close();
    socket.close();

		Prompt.close();
  }
}

 

사용자가 quit 명령을 입력할 때까지 반복

server 버전

1단계 - 클라이언트가 보낸 데이터를 그대로 응답한다.

  • .ServerApp 변경

 

public class ServerApp {

  public static void main(String[] args) throws Exception {
    System.out.println("[PMS 서버]");

    System.out.println("1) 서버 소캣 준비");
    ServerSocket serverSocket = new ServerSocket(8888);

    System.out.println("2) 클라이언트의 접속을 기다림");
    Socket socket = serverSocket.accept(); // 클라이언트가 접속하면 리턴한다.

    System.out.println("3) 클라이언트가 접속했음");

    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(socket.getOutputStream());

    while (true) {
      String command = in.readLine(); // 클라이언트에서 한 줄의 문자열을 보낼 때까지 기다린다.
      System.out.println("===> " + command);

      if (command.equalsIgnoreCase("quit")) {
        out.println("goodbye");
        out.flush();
        break;
      }

      out.println(command);
      out.flush();
    }

    System.out.println("4) 클라이언트와의 접속을 끊음");
    out.close();
    in.close();
    socket.close(); 

    System.out.println("5) 서버 소켓 종료");
    serverSocket.close(); // 더 이상 클라이언트의 접속을 수용하지 않는다.
  }
}

 

클라이언트가 quit 명령을 보낼 때까지 요청/응답을 반복

'quit' 명령을 받으면 "goodbye"를 리턴하고 서버를 종료