메뉴 건너뛰기

조회 수 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
번호 제목 날짜 조회 수
» TCP 소켓 프로그래밍 01 - Server/Client 일대일 연결 file 2021.03.31 119
50 System.out.println(); 이클립스에서 자동화기능 사용 file 2016.09.19 5157
49 static멤버와 관련된 예제 2016.09.21 3768
48 static 2016.09.13 3354
47 Spring Boot 프로젝트 생성 file 2016.09.02 4160
46 Singleton Pattern 과 DeadLock file 2023.02.15 74
45 set get 파라미터 2016.08.18 3658
44 Select statements cannot be executed as an update. 에러 해결방법 file 2016.08.29 3846
43 request header 로부터 접속 정보 확인 file 2023.02.15 75
42 Reflection을 활용한 메서드, 필드 값 불러오기. 2021.03.31 122
41 public static void main(String [] args) 2016.09.13 3143
40 No bean name '***Service' is defined 오류나는 이유 및 해결방법 file 2016.08.29 4561
39 MySQL에 All-in-one 설치시 webmaster로 로그인 안되는 문제 해결을 위한 2가지 수정사항 file 2016.08.29 4954
38 My-SQL 을 이용한 JDBC file 2016.09.21 4282
37 log4j에서 로그가 출력되지 않는 문제 수정 2021.03.25 405
36 jstl <c:url value=""> 사용시 ;jsessionid= 붙는 현상 file 2021.03.31 230
35 JSP, Spring, GMail 메일발송 간단 예제 2016.09.12 32791
34 JSON 문자열을 Map 으로 변환하기(Jackson 사용) 2019.01.08 1010
33 JQuery 자동완성 플러그인 JSDT설치 file 2016.09.19 8896
32 jquery 스크롤(scroll) 따라다니는 배너 레이어 / 위로 버튼 / 화면 상단으로 이동 / scroll layer 이벤트 file 2017.07.05 4057
Board Pagination Prev 1 2 3 4 5 6 7 8 Next
/ 8

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved