메뉴 건너뛰기

조회 수 119 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

■ TCP 소켓 프로그래밍 구현 과정


 

 

1. Server측에서는 ServerSocket을 생성하고 accept() 메서드를 호출함으로써 Client의 접속을 대기합니다.

 

2. Client측에서는 Server에 접속을 함으로써 Server와의 통신을 위한 Socket을 생성합니다.

 

3. 마찬가지로 Server측에서 Client 접속이 이루어지면 해당 Client와 통신 할 수 있는 Socket을 반환받습니다.

 

4. Clinet와 Server는 생성된 소켓을 통하여 각각 상대에게 데이터를 내보내기 위한 출력 스트림과 데이터를 읽어 들이기 위한 입력 스트림을 생성합니다.

 

5. 생성된 스트림을 통하여 Server/Client 서로간에 데이터를 송수신합니다.

 

6. 통신이 끝나면 Client와 Server측에서 각각 socket.close()를 해줌으로써 통신을 종료하게 됩니다.

■ 구현

Server측 

public class Server {

    
    public static void main(String arg[])
    {
        Socket socket = null;                //Client와 통신하기 위한 Socket
        ServerSocket server_socket = null;  //서버 생성을 위한 ServerSocket 
        BufferedReader in = null;            //Client로부터 데이터를 읽어들이기 위한 입력스트림
        PrintWriter out = null;                //Client로 데이터를 내보내기 위한 출력 스트림
        
        try{
            server_socket = new ServerSocket(특정 포트 입력);
            
        }catch(IOException e)
        {
            System.out.println("해당 포트가 열려있습니다.");
        }
        try {
            
            System.out.println("서버 오픈!!");
            socket = server_socket.accept();    //서버 생성 , Client 접속 대기
            
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));    //입력스트림 생성
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); //출력스트림 생성
            
            String str = null;
            str = in.readLine();                //Client로부터 데이터를 읽어옴

            System.out.println("Client로 부터 온 메세지 : " + str);
            
            out.write(str);
            out.flush();
            socket.close();
        }catch(IOException e){}
    }
}

Client측

public class Client {
    public static void main(String[] arg)
    {
        Socket socket = null;            //Server와 통신하기 위한 Socket
        BufferedReader in = null;        //Server로부터 데이터를 읽어들이기 위한 입력스트림
        BufferedReader in2 = null;        //키보드로부터 읽어들이기 위한 입력스트림
        PrintWriter out = null;            //서버로 내보내기 위한 출력 스트림
        InetAddress ia = null;
        try {
            ia = InetAddress.getByName("서버 주소 입력");    //서버로 접속
            socket = new Socket(ia,서버가 열어놓은 포트 입력);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            in2 = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
            
            System.out.println(socket.toString());
        }catch(IOException e) {}
        
        try {
            System.out.print("서버로 보낼 메세제 : ");
            String data = in2.readLine();            //키보드로부터 입력
            out.println(data);                        //서버로 데이터 전송
            out.flush();

            String str2 = in.readLine();            //서버로부터 되돌아오는 데이터 읽어들임
            System.out.println("서버로부터 되돌아온 메세지 : " + str2);
            socket.close();
            
        }catch(IOException e) {}
    }
}

 

 

 


List of Articles
번호 제목 날짜 조회 수
31 log4j에서 로그가 출력되지 않는 문제 수정 2021.03.25 405
30 java에서 이전 URL 알아내기 2021.03.25 690
29 Reflection을 활용한 메서드, 필드 값 불러오기. 2021.03.31 122
28 jstl <c:url value=""> 사용시 ;jsessionid= 붙는 현상 file 2021.03.31 228
27 자바 - 공백 문자 제거하기 (trim, replaceAll) file 2021.03.31 173
26 자바 String Class 문자열 처리 함수에 대한 정리 2021.03.31 106
» TCP 소켓 프로그래밍 01 - Server/Client 일대일 연결 file 2021.03.31 119
24 쓰레드 (Thread) 사용하기 file 2021.03.31 104
23 [객체 지향 언어의 이해] 업캐스팅과 다운캐스팅 file 2021.03.31 157
22 HashMap 사용하기 file 2021.03.31 134
21 자바 대소문자 확인하는 방법 file 2023.02.15 130
20 자바 int 값 자리수 구하기 file 2023.02.15 74
19 자바 배열 복사하는 방법 file 2023.02.15 63
18 자바에서 문자열 비교 시 == 가 아닌 equals를 써야하는 이유 file 2023.02.15 114
17 자바 메소드(Method)란 무엇인가? file 2023.02.15 78
16 자바 Statement PreparedStatement 차이 알아보기 file 2023.02.15 53
15 자바 오버라이드, 오버로드 차이 알아보기 file 2023.02.15 70
14 자바 this, super 차이 알아보기 file 2023.02.15 72
13 자바 객체화(인스턴스화) 알아보기 file 2023.02.15 69
12 자바 클래스, 객체, 인스턴스 구분하기 file 2023.02.15 52
Board Pagination Prev 1 2 3 4 5 6 7 8 Next
/ 8

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved