잡동사니에도 사랑을

[21.08.31] Protocol Server와 Client 연동 본문

JAVA_SE/12_network

[21.08.31] Protocol Server와 Client 연동

luvforjunk 2021. 9. 1. 00:27
728x90
반응형

////////Protocol

 

package network;

 

public class Protocol {

         public static final String ENTER = "100";

         public static final String EXIT = "200";

         public static final String SEND_MESSAGE = "300";

}

 

// 1. 서버를 먼저 실행해야 한다

// - 서버 소켓(소켓과는 다르다) : 기다려주는 역할만 한다.

// - 클라이언트가 접속하기를 기다린다

// - Accept해서 클라이언트와 대화 소켓을 만든다

// 클라이언트의 개수만큼 소켓을 만들어주는 거지.

// 2. 클라이언트(서비스 요청하는 사람) 준비되어야 한다. - port번호, 서버 IP, 소켓

 

////////ProtocolServer

 

package network;

 

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.ServerSocket;

import java.net.Socket;

 

public class ProtocolServer {

         private ServerSocket serverSocket;

         private Socket socket;

         private BufferedReader br;

         private BufferedWriter bw;

 

         public ProtocolServer() { // 항상 먼저 실행

                  try {

                           // 하염없이 9500 방을 보면서 Client 들어오길 기다린다

                           serverSocket = new ServerSocket(9500);

                           System.out.print("서버준비완료");

 

                           // 클라이언트가 들어오면 낚아채서 클라이언트와 연결할 소켓을 만들어준다

                           // ServerSocket 역할. 그러곤 대화에 참여하지 않고 본인은 빠짐

                           socket = serverSocket.accept();

 

                           br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                           bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

 

                  } catch (IOException e) {

                           System.out.println("클라이언트와 연결할 없습니다");

                           e.printStackTrace();

                           System.exit(0);

                  }

                  String line = null;

                  while (true) {

                           try {

                                   // 받는

                                   line = br.readLine(); // 100:angel or 200:angel or 300:angel:안녕

 

                                   // 보내는

                                   String[] ar = line.split(":"); // 콜론을 기준으로 나눠주세요

                                   if (ar[0].equals("100")) { // 0번째 방이 100으로 들어왔습니까

                                            bw.write(ar[1] + " 입장\n"); // 클라이언트에게 보내주자 여기서도 엔터값

                                            bw.flush();

 

                                   } else if (ar[0].equals("200")) {

                                            bw.write(ar[1] + " 퇴장\n");

                                            bw.flush();

                                           

                                            br.close();

                                            bw.close();

                                            socket.close();

                                           

                                            System.exit(0);

                                           

                                   } else if (ar[0].equals("300")) {

                                            bw.write("[" + ar[1] + "]" + ar[2] + "\n");

                                            bw.flush();

 

                                   }

                           } catch (IOException e) {

                                   e.printStackTrace();

                           }

 

                  } // while

         } // ProtocolServer

 

         public static void main(String[] args) {

                  new ProtocolServer();

         }

}

 

////////ProtocolClient

 

package network;

 

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;

 

public class ProtocolClient {

         private Socket socket; // 핸드폰

         private BufferedReader br, keyboard;

         private BufferedWriter bw;

 

         ProtocolClient() {

 

                  // 소켓 생성(핸드폰 구입)

                  try {

                           socket = new Socket("172.16.11.203", 9500);

 

                           br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                           bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

 

                           // 키보드로 부터 입력받아서

                           keyboard = new BufferedReader(new InputStreamReader(System.in));

 

                  } catch (UnknownHostException e) { // 없는 번호입니다

                           System.out.println("서버를 찾을 없습니다");

                           e.printStackTrace();

                           System.exit(0);

 

                  } catch (IOException e) {

                           System.out.println("서버와 연결할 없습니다");

                           e.printStackTrace();

                           System.exit(0);

                  }

 

                  String msg = null;

                  String line = null;

                  while (true) { // 전화 끊을 때까지 무한루프

 

                           try {

                                   // 서버로 보내는

                                   System.out.print("입력 : ");

                                   msg = keyboard.readLine(); // 엔터 바로 전까지 보내기 때문에

                                   bw.write(msg + "\n"); // 엔터를 같이 보내준다. 안그러면 기찻길마냥 한줄로 쭈욱 나온다

                                   // 서버로 보내기(100:angel or 200:angel or 300:angel:안녕)

                                   bw.flush(); // 버퍼를 비워줘야 다음 데이터를 받을 있기 때문에

 

                                   // 서버로부터 받는

                                   line = br.readLine(); // "angel 입장", "angel 퇴장", "[angel] 안녕"

                                   System.out.println(line);

 

                                   String[] ar = msg.split(":"); // "100", "angel" or "200", "angel"

                                   if (ar[0].equals("200")) { // 전화 끊자~~

                                            br.close(); // 알겠어~~

                                            bw.close();

                                            socket.close();

 

                                            keyboard.close();

 

                                            System.exit(0);

                                   }

 

                           } catch (IOException e) {

                                   e.printStackTrace();

                           }

                  }

         } // ProtocolClient()

 

         public static void main(String[] args) {

                  new ProtocolClient();

         }

}

728x90
반응형

'JAVA_SE > 12_network' 카테고리의 다른 글

[21.08.31] URLMain  (0) 2021.09.01
[21.08.31] InetAddress  (0) 2021.09.01