1 / 150

Chap 16. Network Programming

Chap 16. Network Programming. 네트워크 기본개념. 네크워크란 ? 실시간으로 데이터를 송 / 수신하는 컴퓨터와 장비들을 링크를 통해 연결해 놓은 집합 노드 네트워크 상의 기계장치들 ( 컴퓨터 , 프린터 , 라우터 , 브릿지 , 게이트웨이 ) 주소 노드를 유일하게 구별해 주는 일련의 바이트 도메인 이름 ( 노드의 이름 ) 노드들을 쉽게 구별해 주는 노드의 이름. 네트워크 기본개념 ( 계속 ). 네트워크 계층 구조 (TCP/IP). 논리경로. 어플리케이션 계층.

oma
Download Presentation

Chap 16. Network Programming

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. Chap 16. Network Programming

  2. 네트워크 기본개념 • 네크워크란? • 실시간으로 데이터를 송/수신하는 컴퓨터와 장비들을 링크를 통해 연결해 놓은 집합 • 노드 • 네트워크 상의 기계장치들 (컴퓨터, 프린터, 라우터, 브릿지, 게이트웨이) • 주소 • 노드를 유일하게 구별해 주는 일련의 바이트 • 도메인 이름(노드의 이름) • 노드들을 쉽게 구별해 주는 노드의 이름

  3. 네트워크 기본개념 (계속) • 네트워크 계층 구조(TCP/IP) 논리경로 어플리케이션 계층 어플리케이션 계층 전송 계층(TCP, UDP) 전송 계층(TCP, UDP) 인터넷 계층 인터넷 계층 네트워크 인터페이스 (이더넷, 토큰버스, 토큰링, FDDI 등)

  4. 네트워크 기본개념 (계속) • 전송 계층 • 패킷이 순서대로 도착했는지, 손실된 패킷은 없는지를 검사 • TCP : 손실된 패킷을 재전송, 순서대로 도착하게 함 (overload가 많음) • UDP : 패킷의 도착 순서에 무관 (overload가 적음) • 어플리케이션 계층 • 데이터를 사용자에게 전달하는 계층

  5. 네트워크 기본개념 (계속) • 포트 • 어플리케이션을 구별하기 위해 사용되는 번호 • 각 포트는 특정한 서비스를 제공하기 위해 사용 • 1~65535사이의 숫자가 할당 (1 ~1024는 잘 알려진 서비스를 위해 예약)

  6. 네트워크 기본개념 (계속) • 클라이언트 / 서버 모델 • 큰 용량의 데이터들을 비싸고 고성능인 서버에 저장 • 프로그램 로직이나 사용자 인터페이스는 저가인 클라이언트에서 실행 • 서버의 종류 • 파일 서버, 데이터 베이스 서버  데이터를 가공하지 않고 클라이언트에 보냄 • 어플리케이션 서버  데이터를 분석하고 처리해서 클라이언트에 보냄

  7. 네트워크 기본개념 (계속) • 호스트 • 인터넷에 연결된 장치들. • 호스트는 컴퓨터, 라우터, 프린터, 팩스장치, 워크스테이션, 등등을 지칭.

  8. 네트워크 기본개념 (계속) • 포트 • 호스트는 단 하나의 IP 주소를 가짐. • 한 IP 주소에 65,536개의 포트가 할당 가능. • 다른 호스트들과 통신하기 위해 하나의 호스트에 할당된 논리적인 개념.

  9. 네트워크 기본개념 (계속) • IP 주소 • 모든 호스트는 4 바이트의 유일한 IP주소로 식별 . • IP 주소는 0부터 255사이의 값을 갖는 4개의 부호 없는 바이트로 구성.

  10. InetAddress 클래스 Java.net 패키지 ContenHandler DatagramPacket DatagramSocket MulticastSocket DatagramSocketImpl InetAddress Object SeverSocket Socket SocketImpl URL URLConnection HttpURLConnection URLEncoder URLStreamHandler

  11. InetAddress 클래스(계속) • InetAddress 클래스 • InetAddress클래스의 생성자는 없음. • java.net.InetAddress클래스는 IP 주소 표현. • 숫자형 주소를 호스트 이름으로, 호스트 이름을 숫자형 주소로 변환 • 호스트를 식별학기 위해 소켓이나 서버소켓과 같은 다른 네트워크 클래스에 의해 사용

  12. InetAddress 클래스(계속) 메 소 드설 명 boolean equals(InetAddressother) 현 객체가 other객체와 같은 주소를 가지면 true, 아니면 false를 반환 byte[] getAddress()주소를 나타내는 4개의 요소를 가진 바이트 배열을 반환 String getHostAddress()주소 정보를 나타내는 문자열을 반환 String getHostName()컴퓨터 이름을 나타내는 문자열을 반환 InetAddressgetLocalHost()현재 컴퓨터를 나타내는 InetAddress객체를 반환 throws UnknownHostException InetAddressgetByName(String hostName) hostName으로 지정된 컴퓨터를 나타내는 throws UnknownHostException InetAddress객체를 반환 InetAddress[] getAllByName(String hostName) hostName으로 지정된 모든 컴퓨터(하나의 throws UnknownHostException도메인 이름으로 여러 대의 컴퓨터를 사용하는 경우)를 나타내는 InetAddress객체들의 배열을 반환 InetAddress 클래스의 주요 메소드

  13. 예제) IP주소 알아내기 import java.net.*; publicclass InetDemo{ publicstaticvoid main(String a[]) throws Exception{ InetAddress ia; ia= InetAddress.getLocalHost(); System.out.println("LocalHost의 IP 주소: " + ia.getHostAddress()); ia = InetAddress.getByName("www.naver.com"); System.out.println("naver의 IP 주소: " + ia.getHostAddress()); System.out.println("naver의 호스트 이름: " + ia.getHostName()); } }

  14. 결과)인터넷에 연결 안된 상태/연결상태 - LocalHost의 IP 주소: 127.0.0.1 java.net.UnknownHostException: www.naver.com at java.net.InetAddress.getAllByName0(InetAddress.java:571) at java.net.InetAddress.getAllByName0(InetAddress.java:540) at java.net.InetAddress.getByName(InetAddress.java:449) at InetDemo.main(InetDemo.java:10) Exception in thread "main" Process Exit... - LocalHost의 IP 주소: 61.79.132.105 naver의 IP 주소: 211.218.150.135 naver의 호스트 이름: www.naver.com Process Exit...

  15. InetAddress 클래스(계속) • 새로운 InetAddress 객체 생성하기 • 공용(public) 생성자가 없음. • 3개의 정적 메소드가 존재.

  16. InetAddress 클래스(계속) • Public static InetAddress InetAddress.getByName(String hostname) • 호스트 이름을 인자로 넘겨 받아, 이에 매칭되는 IP주소를 찾기 위해 DNS 이용. • 호출 예 • InetAddress address = InetAddress.getByName(“www.oreilly.com”)

  17. InetAddress 클래스(계속) 예제: www.oreilly.com의 주소를 출력하는 프로그램 import java.net.*; class oreilly { public static void main (String args[]) { try { InetAddress address = InetAddress.getByName("www.oreilly.com"); System.out.println(address); } catch (UnknownHostException e) { System.out.println("Could not find www.oreilly.com"); } } } InetAddress 객체를 생성 호스트를 발견하지 못하면getByName() 메소드는 UnknownHostException을 발생 출력 결과 www.oreilly.com/204.148.40.9

  18. InetAddress 클래스(계속) 예제 4.2 : 204.29.207.217의 주소를 출력하는 프로그램 import java.net.*; class OreillyByAddress { public static void main (String args[]) { try { InetAddress address = InetAddress.getByName("204.29.207.217"); System.out.println(address); } catch (UnknownHostException e) { System.out.println("Could not find 204.29.207.217"); } } } 호스트 이름이 없는 기계에 접속할 때 수치형 IP주소가 문자열 형태로 전달 출력 결과 : 204.29.207.217/ 204.29.207.217

  19. InetAddress 클래스(계속) • 그 외의 메소드 • public static InetAddress[ ] getAllByName (String host) throws UnknownHostExeption • public static InetAddress getLocalHost ( ) throws UnknownHostExeption

  20. InetAddress 클래스(계속) • Public static InetAddress InetAddress.getAllByName(String hostname) • 호스트 이름과 매칭되는 모든 InetAddres를 담고 있는 배열을 반환 • 호출 예 • InetAddress address = InetAddress.getAllByName(“www.ora.com”)

  21. InetAddress 클래스(계속) 예제 4.3 : www.apple.com의 모든 주소를 출력하는 프로그램 import java.net.*; class apple { public static void main (String args[]) { try { InetAddress[] addresses = InetAddress.getAllByName("www.apple.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException e) { System.out.println("Could not find www.apple.com"); } } } • 호스트 이름과 매칭되는 모든 InetAddres를 담고 있는 배열을 반환 출력 결과 : www.apple.com/17.254.0.91

  22. InetAddress 클래스(계속) • Public static InetAddress InetAddress.getLocalHost( ) • 프로그램이 실행되고 있는 호스트의 InetAddress 반환 • 호출 예 • InetAddress thisComputer = InetAddress.getLocalHost( );

  23. InetAddress 클래스(계속) 예제 4.4: 로컬 호스트의 주소 찾기 import java.net.*; class myAddress { public static void main (String args[]) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); } catch (UnknownHostException e) { System.out.println("Could not find this computer's address."); } } } 프로그램이 실행되고 있는 호스트의 InetAddress 반환 출력 결과 : sec/203.247.39.35

  24. InetAddress 클래스(계속) • InetAddress객체를 얻는 기타 방법 • DatagramPacket.getAddress( ) • ServerSocket.getInetAddress( ) • SocketImpl.getInetAddress( ) • Socket.getInetAddress( )

  25. InetAddress 클래스(계속) • 필드 값 구하기 • public String getHostName( ) • public byte[ ] getAddress( )

  26. InetAddress 클래스(계속) • public String getHostName( ) • InetAddress 객체의 호스트 이름을 포함하고 있는 문자열을 반환. • 호스트 이름이 없는 경우, 수치형 IP주소가 문자열 형태로 반환.

  27. InetAddress 클래스(계속) 예제 4.5: 로컬 호스트의 호스트 이름을 찾는다. import java.net.*; class myName { public static void main (String args[]) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println("Hello. My name is " + address.getHostName()); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own name."); } } } • InetAddress 객체의 호스트 이름을 포함하고 있는 문자열을 반환. 출력 결과 : Hello. My name is sec

  28. InetAddress 클래스(계속) • public byte[ ] getAddress( ) • 기계의 IP주소를 알기 위한 메소드 • IP주소를 부호 없는 바이트 배열의 형태로 반환

  29. InetAddress 클래스(계속) 예제 4.6: 로컬 기계의 IP주소 찾기 class MyAddress6 { public static void main (String args[]) { try { InetAddress thisComputer = InetAddress.getLocalHost(); byte[] address = thisComputer.getAddress(); System.out.print("My address is "); for (int i = 0; i < address.length; i++) { int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i]; System.out.print(unsignedByte + "."); } System.out.println(); } IP주소를 바이트 배열의 형태로 반환 부호없는 바이트의 처리 부분 출력 결과 : My address is 203.247.39.35.

  30. InetAddress 클래스(계속) • 객체 메소드들 • public boolean equals(Object anyobject) • public int hashCode( ) • Public String toString( )

  31. InetAddress 클래스(계속) • public boolean equals(Object anyobject) • 동일 객체 검증 메소드 • InetAddress 클래스의 인스턴스이고, 4바이트의 IP주소가 동일. • 호스트 이름이 같을 필요는 없음.

  32. InetAddress 클래스(계속) 예제 4.7: spacecadet와 macfaq 는 같은가? class macfaq { public static void main (String args[]) { try { InetAddress macfaq = InetAddress.getByName("www.macfaq.com "); InetAddress spacecadet = InetAddress.getByName("spacecadet.cnet.com"); if (macfaq.equals(spacecadet)) { System.out.println ("www.macfaq.com is the same as spacecadet.cnet.com");} else { System.out.println ("www.macfaq.com is not the same as spacecadet.cnet.com");} } 두 객체가 같으면 true, 다르면 false 출력 결과 : Host lookup failed.

  33. InetAddress 클래스(계속) • public int hashCode( ) • hashAddress객체가 해시 테이블의 키로 사용될 경우 필요한 정수 값 반환. • Java.util.Hashtable의 메소드에 의해 호출. • Address 필드의 값 반환. • 16바이트 주소로의 수정이 어려움.

  34. InetAddress 클래스(계속) • Public String toString( ) • 생성 문자열 • [호스트 이름/] IP주소 • 사용법 • InetAddress thisComputer = InetAddress.getLocolHost( ) • String address = thisComputer.toString( );

  35. JavaTM2Platform StandardEdition java.lang.Object java.applet java.awt java.io …… java.net javax.swing …… InetAddress Socket URL URLEncoder ServerSocket ……

  36. java.net.URL의 클래스 • URL은 원래 WWW상에 존재하는 자원의 위치를 표시하기 위한 것. • URL은 프로토콜, 호스트 ID, 포트, 디렉토리, 파일로 구성 • 사용형식 : protocol://domain_name:port_no/path/file_name 예) http://ikim.hansung.ac.kr/cgi/index.html/#A12.2.2 - 프로토콜 : http - 호스트 : ikim.hansung.ac.kr - port : 80 (기본값) - 디렉토리 : cgi - 파일명 : index.html - 섹션필드(참조) : #A12.2.2

  37. java.net.URL의 클래스

  38. URL 클래스의 생성자 • 생성자 • URL(Stringspec) • URL(Stringprotocol, Stringhost, Stringfile) • URL(Stringprotocol, Stringhost, intport, Stringfile) • URL(Stringprotocol, Stringhost, intport, Stringfile, URLStreamHandlerhandler) • URL(URLcontext, Stringspec) • URL(URLcontext, Stringspec, URLStreamHandlerhandler) • 생성방법 • new URL(…) • 모든 URL 생성자는 MalformedURLException을 발생 • 자바가 지원하지 않는 프로토콜에 대한 URL을 생성하려고 할 경우 발생한다. • HTTP,FTP,news, mailto, gopher, file 지원

  39. URL 클래스의 생성자 • public URL(String url) throws MalformedURLException • 예제 • import java.net.*; public class URLConstructorTest1 { public static void main(String[] args) { URL webURL,ftpURL; try { webURL = new URL(“http://www.macfaq.com/vendor.html”); System.out.println(webURL); ftpURL = new URL(“ftp://ftp.macfaq.com/pub/”); System.out.println(ftpURL); } Catch (MalformedURLException e) { System.err.println(e); } } } • 결과 http://www.macfaq.com/vendor.html java.net.MalformedURLException: ftp//ftp.macfaq.com/pub/:java.lang.Exception

  40. URL 클래스의 생성자 • public URL(String protocol, String host, String file) throws MalformedURLException • 포트번호는 –1로 할당하여 기본 값 포트 번호가 사용됨 • file을 나타내는 문자열은 슬래쉬(/)로 시작 • 예제 • try { URL u = new URL(“http”,www.macfaq.com,”/blueribbon.html#intro”); } catch (MalformedURLException e) { System.out.println(e); }

  41. URL 클래스의 생성자 • public URL(String protocol, String host, int port, String file) throws MalformedURLException • 기본값 포트 번호가 다를 경우 사용 • 예제 try { URL u = new URL(“http”,”www.eff.org”,80,”/blueribbon.html#intro”); } catch ( MalformedURLException e) { System.err.println(e); }

  42. URL 클래스의 생성자 • public URL(URL u, String s) throws MalformedURLException • 상대 URL을 이용하여 절대 URL을 생성할 경우 사용 • 같은 디렉토리 안에 있는 여러 파일을 처리하는 경우 유용 • 예제 • 디렉토리구조 user/public_html/html/examples.html user/public_html/html/vendor.html user/public_html/applet/URLConstructorTest4.class • examples.html <html> <body> <applet code = “.. /applet/URLConstructorTest4.class”> </body> </html>

  43. URL 클래스의 생성자 • 예제 • import java.net.*; import java.applet.Applet; public class URLConstructorTest4 extends Applet { public void init() { URL u1, u2; u1 = getDocumentBase(); System.out.println(u1); try { u2 = new URL(u1, “vendor.html”); System.out.println(u2); } Catch (MalformedURLException e) { System.err.println(e); } } } • 결과 • File: user/public_html/html/examples.html File: user/public_html/html/vendor.html

  44. URL 조각내기 • URL class의 Methods • Protocol : getProtocol() • Host : getHost() • Port : getPort() • File : getFile() • Ref : getRef() • URLStreamHandler

  45. URL class의 Methods • public String getProtocol() • URL의 프로토콜 부분을 String로 반환한다. • public String getHost() • URL의 호스트 이름 부분을 String로 반환한다. • public String getPort() • URL이 지정하고 있는 포트번호를 int로 반환한다. • 포트번호가 명시되지 않으면 –1을 반환

  46. URL class의 Methods • public String getFile() • URL의 경로와 파일 부분을 String로 반환한다. • 호스트이름의 첫 슬래쉬(/)에서 파일내 참조를 알리는 파운드 기호(#)까지의 모든 문자 • 파일이름이 없을 경우 ‘/’를 반환 • public String getRef() • URL의 파일 내 참조 위치를 반환한다. • URL이 파일내 참조위치를 갖고 있지 않을 경우 Null을 반환한다.

  47. URL class의 Methods 예제 예제 import java.net.*; public class getURLParts { public static void main(String args[]) { try { URL u = new URL(args[0]); System.out.println( u ); System.out.println( u.getProtocol() ); System.out.println( u.getHost() ); System.out.println( u.getPort() ); System.out.println( u.getFile() ); System.out.println( u.getRef() ); } catch (MalformedURLException e ) { System.out.println( e ); } } }

  48. URL class의 Methods 예제 결과 $ java getURLParts http://www.ncsa.uiuc.edu/demoweb/html-primer.html#A1.3.3 http://www.ncsa.uiuc.edu/demoweb/html-primer.html#A1.3.3 http www.ncsa.uiuc.edu -1 /demoweb/html-primer.html A1.3.3

  49. URL에서 데이터를 가져오기 위한 메소드 • public final InputStream openStream() throws IOException • URL이 가리키고 있는 자원에 연결 • 클라이언트와 서버간의 핸드셰이킹(handshaking) • 데이터를 읽어 들이기 위한 InputStream을 반환 • 파일의 원시 컨텐트를 반환하고 HTML의 헤더나 프로토콜의 정보는 들어 있지 않다. • 예제 URL u = new URL(“http://www.hannam.ac.kr”); DataInputStream theHTML = newDataInputStream(u.openStream()); While ( ( thisLine = theHTML.readLine()) != null ) System.out.println(this.Line);

  50. URL에서 데이터를 가져오기 위한 메소드 • public URLConnection openConnection() throws IOException • URL에 소켓을 열고 URLConnection객체를 반환한다. • 네트워크 자원에 대한 연결 • 서버와 직접 통신하기를 원할 때 쓰는 메소드 • 원시형태의 문서와 사용중인 프로토콜의 헤더정보를 볼 수 있다. • URLConnection은 10장 참조 • 예제 URL u = new URL(“http://www.hannam.ac.kr”); URLConnection uc = u.openConnection();

More Related