1 / 35

9. UDP 데이터그램 과 소켓

9. UDP 데이터그램 과 소켓. 2000. 6. 2. 강 동 호 컴퓨터 네트워크 실험실. 목차. 개요 DatagramPacket 클래스 DatagramSocket 클래스 데이터그램 수신과 송신 소켓 옵션 추상화의 상위수준 유용한 프로그램 요약. 개 요. UDP(User Datagram Protocol) 데이터그램 비연결형 데이터 전달 서비스를 제공하는 전달 계층 프로토콜 신뢰성이나 데이터의 전달 순서를 보장하지 않는다 . 신뢰성보다 속도가 중요시 되는 데이터의 전송에 이용

Download Presentation

9. UDP 데이터그램 과 소켓

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 9. UDP 데이터그램 과 소켓 2000. 6. 2 강 동 호 컴퓨터 네트워크 실험실

  2. 목차 • 개요 • DatagramPacket 클래스 • DatagramSocket 클래스 • 데이터그램 수신과 송신 • 소켓 옵션 • 추상화의 상위수준 • 유용한 프로그램 • 요약

  3. 개 요 • UDP(User Datagram Protocol) 데이터그램 • 비연결형 데이터 전달 서비스를 제공하는 전달 계층 프로토콜 • 신뢰성이나 데이터의 전달 순서를 보장하지 않는다. • 신뢰성보다 속도가 중요시 되는 데이터의 전송에 이용 • TCP - 전화, UDP - 편지

  4. 개 요 (Cont’d) • UDP • Connection-Less mode • Unreliable service • TCP • Connection-Oriented mode • Reliable service

  5. 개 요 (Cont’d) • UDP 데이터그램 형식 32비트 근원지 포트 목적지 포트 길이 체크섬 데이터

  6. 개 요 (Cont’d) • 자바의 UDP 구현에 필요한 클래스 • DatagramPacket • 데이터를 데이터그램이라는 UDP패킷에 채워 넣고, 도착한 데이터그램에서 데이터를 꺼낼수 있도록 한다. • DatagramSocket • 데이터를 보내고, 받는 역할을 한다.

  7. DatagramPacket 클래스 • public DatagramPacket(byte buffer[ ], int length) • 데이터를 받기 위해 DatagramPacket 객체를 만드는 생성자 • buffer[ ]: 데이터가 위치해 있는 바이트 배열 • length: 버퍼의 길이(buffer.length보다 긴 DatagramPacket을 생성하려고 하면, lIIegalArgumentException 에러 발생)

  8. DatagramPacket 클래스 (Cont’d) • 데이터를 수신하는 DatagramPacket 생성하기 import java.net.*; public class UDPReceiver { public static void main (String args[ ]) { byte[] buffer = new byte[8096]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); } }

  9. DatagramPacket 클래스 (Cont’d) • public DatagramPacket(byte buffer[ ], int length, InetAddress ia, int port) • 다른 호스트로 전송할 DatagramPacket 생성 • buffer[ ]: 전송할 데이터의 바이트 배열 • length: 버퍼의 길이(buffer.length보다 큰 length를 갖는 DatagramPacket을 생성하려고 하면, IllgalArgumentException이 발생한다.) • InetAddress ia: 패킷의 목적지 호스트 주소 • Port: 목적지 포트 번호

  10. DatagramPacket 클래스 (Cont’d) • 데이터를 보내기 위해 DatagramPacket을 생성하기 import java.net.*; Public class UDPSender { Public static void main(String args[]) { String s = “this is a test.”; byte[] data = new byte[s.length()]; S.getBytes(0, s.length(),data, 0); try { lnetAddress ia = lnetAddress.getByName(“sunsite.unc.edu”); Int port = 7; DatagramPacket = new DatagramPacket(data, data.length, ia, port); } Catch (UnknownHostException e) { } } }

  11. get 메소드들 • 데이터그램의 정보 제공 • public InetAddress getAddress( ) • 원격호스트의 주소를 가진 InetAddress객체를 반환 • 임의의 네트워크로부터 수신된 것이라면, 데이터그램을 보낸 호스트의 주소를 반환 • 데이터그램을 전송하기 위해 로컬 호스트에서 생성된 것이라면, 데이터그램이 보내질 호스트의 주소를 반환

  12. get 메소드들 (Cont’d) • public int getPort( ) • 원격기계의 데이터그램 포트 번호를 정수로 반환 • public byte[] getData( ) • 데이터그램 안에 들어있는 데이터들을 바이트 배열로 반환 • 다른 데이터형(String형)으로의 변환 • Public String(byte[] buffer, int high_byte, int start, int num_bytes) String s = new String(dp.getData(), 0, 0,dp.getLength()); //데이터그램에 들어있는 데이터가 아스키 텍스트일 경우

  13. get 메소드들 (Cont’d) • Public ByteArrayInputStream(byte[] buffer, int offset, int num_byte) ByteArrayInputStream bis = new ByteArrayInputStream(dp.getData( ), 0, 0, dp.getLength( )); DataInputStream dis = new DataInputStream(bis); //아스키 텍스트가 아닌 경우 • Public int getLength( ) • 데이터의 바이트 수 반환

  14. get 메소드들 (Cont’d) • 데이터 전송을 위한 DatagramPacket을 생성하기 String s = "This is a test."; byte[] data = new byte[s.length()]; s.getBytes(0, s.length(), data, 0); try { InetAddress ia = InetAddress.getByName(“netwk.hannam.ac.kr"); int port = 7; DatagramPacket dp = new DatagramPacket(data, data.length, ia, port); System.out.println("This packet is addressed to " + dp.getAddress() + “ on port " + dp.getPort()); System.out.println("There are " + dp.getLength() + " bytes of data in the packet"); System.out.println(new String(dp.getData(), 0, 0, dp.getLength())); }

  15. DatagramSocket 클래스 • UDP에서 데이터그램을 보내거나 받을때 사용되는 유일한 소켓 클래스 • Public DatagramSocket( ) throws SocketException • 익명 포트에 바인드 되는 DatagramSocket을 생성 public static void main(String[] args) { try { DatagramSocket theClient = new DatagramSocket(); } }

  16. DatagramSocket 클래스 (Cont’d) • Public DatagramSocket(int port) throws SocketException • 지정된 특정 포트에서, 들어오는 데이터그램을 기다리는 DatagramSocket 생성 • 객체 생성 실패 원인 • 지정된 포트가 이미 사용중일 때 • 1024번 이하의 포트를 사용하려고 할때 • 소켓 생성 실패시 SocketException 발생

  17. DatagramSocket 클래스 (Cont’d) Import java.net.*; public class lookForLocalUDPPorts { public static void main(String[ ] args) { DatagramSocket theServer; for (int i = 1024; i <= 65535; i++) { try { theServer = new DatagramSocket(i); theServer.close(); } catch (SocketException e) { System.out.println("There is a server on port " + i + "."); } } }}

  18. DatagramSocket 클래스 (Cont’d) • Public DatagramSocket(int port, lnetAddress intf) throws SocketException • 지정된 포트와 지정된 네트워크 인터페이스에서 들어오는 데이터그램을 위해 연결요청을 기다리는 소켓을 생성 • Port: 소켓이 데이터그램을 위해 연결 요청을 기다리는 포트 • Intf: 호스트의 네트워크 주소중의 하나에 대한 lnetAddress객체이다. • 자바 1.1에서만 지원

  19. 데이터그램 주고 받기 • public void send(DatagramPacket dp) throws IOExecption • DatagramPacket이 생성되고, DatagramSocket이 열리면 소켓의 send() 메소드에 패킷을 넘김으로써 데이터를 전송할 수 있다. • theSocket.send(theOutput);

  20. 데이터그램 주고 받기 (Cont’d) • Public void receive(DatagramPacket dp) throws IOException • 네트워크를 통해 수신된 UDP 데이터그램을 DatagramPacket객체로 변환한다.

  21. 데이터그램 주고 받기 (Cont’d) • Public int getLocalPort() • 로컬기계에서 소켓이 귀를 기울이고 있는 포트의 번호를 int로 반환 • 익명 포트를 사용해서 DatagramSocket을 생성한 경우, 사용중인 포트 번호를 알고자 할 때 이 메쏘드를사용 하면 된다.

  22. 데이터그램 주고 받기 (Cont’d) import java.net.*; public class getLocalPortExample { public static void main(String[] args) { try { DatagramSocket ds = new DatagramSocket(); System.out.println("The DatagramSocket is on port " + ds.getLocalPort()); } catch (SocketException e) { } } }

  23. 데이터그램 주고 받기 (Cont’d) • Public synchronized void close( ) • 소켓이 사용하고 있는 포트의 해제 try { DatagramSocket theServer = new DatagramSocket(); theServer.close(); }

  24. 소켓 옵션 (자바 1.1) • 자바1.1에서 데이터그램 소켓에 대해 지원이 되는 소켓 옵션은 SO_TIMEOUT뿐이다. • Public synchronized void setSoTimeout(int timeout) throws SocketException • 데이터그램 소켓의 SO_TIMEOUT필드에 값을 설정한다. • receive() 메쏟가 연결 요청 신화를 기다려야하는 시간을 milliseconds단위로 설정한다. • 설정된 시간이 지나면, InterruptedException이 발생한다. • 정해진 시간내에 응답이 와야 하는 보안관련 프로토콜 작성시에 사용된다.

  25. 소켓 옵션 (자바 1.1) (Cont’d) try { buffer = new byte[2056]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); DatagramSocket ds = new ServerSocket(2048); ds.setSoTimeout(30000); try { ds.receive(dp); ..... } catch (InterruptedExecption e) { ds.close (); System.err.println(" No connection within 30 seconds"); }

  26. 소켓 옵션 (자바 1.1) (Cont’d) • Public synchronized int getSoTimeout() throws IOException • getSoTimeout()메소드는 현재 DatagramSocket객체의 SO_TIMEOUT필드 값을 반환한다. int timeout = ds.getSoTimeout( );

  27. 객체 메소드들 • Protected synchronized void finalize() • DatagramPacket 또는 DatagramSocket에 의해서 치환되는 java.lang.Object의 유일한 메소드 • DatagramSocket객체가 쓰레기 수거되기 전에 호출된다.

  28. 추상화의 상위수준 • UDPClient • 데이터를 보내기 전에 바이트 배열을 DatagramPacket 객체로 변환할 필요가 없고, 데이터그램을 수신하기 위해 빈버퍼를 가진 DatagramPacket을 생성할 필요도 없다. • 인터넷 주소와 포트 번호를 인자로 넘김으로써 UDPClient객체를 생성한다.

  29. 유용한 프로그램 • 호스트는 패킷의 IP헤더 부분을 조사해서 TCP 패킷 인지 UDP패킷 인지를 판별할수 있다. • TCP 서버와 UDP서버는 아무런 문제없이 같은 포트 번호를 공유할 수 있다.

  30. 유용한 프로그램 (Cont’d) • 간단한 UDP 클라이언트 • 몇몇 인터넷 서비스는 클라이언트의 주소와 포트번호만을 필요로 한다. • 서버측에서는 데이터 그램내에 있는 데이터를 그냥 버린다. • daytime(13포트),quote(17포트) ,chargen(19포트)

  31. 유용한 프로그램 (Cont’d) • UDP 서버 • 하나의 UDP 서버 클래스를 만들어, 특수한 프로토콜을 구현하는 서버는 서버 클래스로 만드는 개념

  32. 유용한 프로그램 (Cont’d) • UDP echo 클라이언트 • echo 프로토콜을 UDP로 구현하기 어려운점 • I/O 스트림을 지원하지 않는다. • 연결이라는 개념이 존재하지 않는다. • UDP에서는 데이터를 보내고 받는 프로세스가 비동기적으로 이루어져야 한다. => Thread를 이용 • UDPEchoClient, echoInputThread, echoOutputThread 클래스로 구성된다.

  33. 유용한 프로그램 (Cont’d) • UDPEchoClient 클래스 • 명령어 입력 라인에서 호스트이름을 읽어 들이고, 소켓 생성 후 echoInputThread 클래스, echoOutputThread클래스를 실행시킨다. • echoInputThread 클래스 • 사용자로 부터 입력을 한번에 한줄씩 읽어 들여, 이를 echo 서버에게 전송한다.

  34. 유용한 프로그램 (Cont’d) • echoOutputThread 클래스 • 데이터그램이 도착할 때 까지 대기하다가 수신되면, 그것을 String으로 변환하여 출력한다.

  35. 요 약 • DatagramPacket 클래스 • 데이터를 데이터그램이라는 UDP패킷에 채워 넣고, 도착한 데이터그램에서 데이터를 꺼낼 수 있도록 하기 위한 DatagramPacket 객체를 생성한다. • DatagramSocket 클래스 • 데이터그램을 송수신하기 위한 DatagramSocket 객체를 생성한다.

More Related