메뉴 건너뛰기

조회 수 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
번호 제목 날짜 조회 수
111 public static void main(String [] args) 2016.09.13 3143
110 Reflection을 활용한 메서드, 필드 값 불러오기. 2021.03.31 122
109 request header 로부터 접속 정보 확인 file 2023.02.15 75
108 Select statements cannot be executed as an update. 에러 해결방법 file 2016.08.29 3846
107 set get 파라미터 2016.08.18 3658
106 Singleton Pattern 과 DeadLock file 2023.02.15 74
105 Spring Boot 프로젝트 생성 file 2016.09.02 4160
104 static 2016.09.13 3354
103 static멤버와 관련된 예제 2016.09.21 3768
102 System.out.println(); 이클립스에서 자동화기능 사용 file 2016.09.19 5157
» TCP 소켓 프로그래밍 01 - Server/Client 일대일 연결 file 2021.03.31 119
100 war로 묶지 않아도 컴파일된 소스 위치 확인하기 file 2016.08.29 4116
99 XML to JSON , JSON to Map 2020.06.29 262
98 [객체 지향 언어의 이해] 업캐스팅과 다운캐스팅 file 2021.03.31 157
97 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ] 이클립스 프로젝트 생성 순서04.jdbc 드라이버 설치 file 2016.08.18 4209
96 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ] 이클립스 프로젝트 생성 순서07.commons-collection 설치 file 2016.08.18 3845
95 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ] 이클립스 프로젝트 생성 순서08.commons-logging 설치 file 2016.08.18 4458
94 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ]11. 이클립스 프로젝트 생성 file 2016.08.18 3972
93 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ]9. 이클립스 압타나 플러그인 설치 file 2016.08.18 4012
92 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동]3. 이클립스 설치 file 2016.08.18 3756
Board Pagination Prev 1 2 3 4 5 6 7 8 Next
/ 8

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved