
1-1. 프로토콜이란?

프로토콜은 서로의 약속이다. 마치 아스키 코드처럼, 1을 받으면 '영화'라고 출력해야 한다고 약속하는 것 만약, 1이나 2를 보내지 않으면 exception이 발생하게끔 코드를 짠다!

1-2. 반이중 통신 만들기
[ PrintWriter ]
BufferedWriter로 만들면 new writeStream 뭐 이렇게 길게 만들어야 하거든? 귀찮잖아 PrintWriter로 간단하게 만들 수 있다.
//버퍼 만들기 (send) 1. PrintWriter pw = new PrintWriter(socket.getOutputStream(), true, Charset.forName("UTF-8")); 2. PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
true = flust() 유무
PrintWriter 안에 BufferedWriter가 구현되어 있고, autoFlush도 boolean 으로 구현되어 있음. 즉, flush()를 작성하지 않고 true만 입력해도 됨!



UTF-8도 달려있어서 1번째 코드처럼 안써도 됨.
[ 전체 코드 ]
[ 프로토콜 ]
<protocol.txt> 1 -> 영화 2 -> 드라마
[ Server ]
package ex17.half; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(20000); Socket socket = serverSocket.accept(); //소켓 연결 완료됨 //버퍼 만들기 (received) BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String requestMsg = br.readLine(); System.out.println("클라이언트로부터 받은 메시지 : " + requestMsg); //버퍼 만들기 (send) PrintWriter pw = new PrintWriter(socket.getOutputStream(), true, Charset.forName("UTF-8")); //프로토콜. 마치 아스키 코드처럼 1을 받으면 영화라고 출력 //서버 입장에선 클라이언트한테 받는 responseMsg if (requestMsg.equals("1")) { pw.println("영화"); } else if (requestMsg.equals("2")) { pw.println("드라마"); } else { pw.println("프로토콜을 확인하세요 : 1은 영화, 2는 드라마"); } //역슬래시를 몇 번 날릴지 모르기때문에 원랜 while을 돌려야함. 지금은 생략 } catch (IOException e) { throw new RuntimeException(e); } } }
[ Client ]
package ex17.half; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { public static void main(String[] args) { try { //클라이언트에 소켓이 생겼으니, 서버와 소켓과 클라이언트 소켓이 연결되었겠구나 //포터번호가 20000이니, 서버의 소켓에 연결한게 맞지! Socket socket = new Socket("localhost", 20000); //고객은 처음에 쓸거니까 PrintWriter를 먼저 단다 PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); //클라이언트 입장에선 request 메세지. //이 숫자를 보고 통신함. 1을 보내면 영화가 출력될 것 pw.println("1"); //이제 읽어야겠지? 응답한거 답하려고 버퍼드리더 3handshack? BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String responseMsg = br.readLine(); System.out.println("서버로 부터 받은 메시지 : " + responseMsg); } catch (IOException e) { throw new RuntimeException(e); } } }
[ 결과 ]


만약 3을 입력하면?


반이중 통신은 양방향으로 통신할 수는 있지만 동시에 통신할 수는 없다! (ex. 무전기처럼)
Share article