Presentation is loading. Please wait.

Presentation is loading. Please wait.

8장. 네트워크 프로그래밍 /*컴퓨터 네트워크 프로그래밍 -김화종 저- 참조 */

Similar presentations


Presentation on theme: "8장. 네트워크 프로그래밍 /*컴퓨터 네트워크 프로그래밍 -김화종 저- 참조 */"— Presentation transcript:

1 8장. 네트워크 프로그래밍 /*컴퓨터 네트워크 프로그래밍 -김화종 저- 참조 */
네트워크 프로그래밍의 분류 디바이스 드라이버 프로그래밍: 통신 장비(device)를 직접 구동 API로 FTP사의 패킷 드라이버(Packet Driver), 마이크로소프트사의 NDIS(Network Driver Interface Specification), 노벨사의 ODI(Open Data Interface) 소켓 프로그래밍: TCP와 같은 트랜스포트 계층의 인터페이스를 이용 응용 계층 프로그래밍: 응용 계층을 이용

2 소켓 프로그래밍 소켓(socket)은 1982년 BSD(Berkeley Software Distribution) UNIX 4.1에서 처음 소개 현재 사용되는 것은 1986년의 BSD UNIX 4.3에서 개정된 것 소켓은 소프트웨어로 작성된 통신 접속점이라고 할 수 있는데 네트웍 응용 프로그램은 소켓을 통하여 통신망으로 데이터를 송수신 소켓은 응용 프로그램에서 TCP/IP를 이용하는 창구 역할

3 소켓번호 UNIX에서 파일을 새로 열면(open) int 타입의 정수를 리턴하는데 이와같이 open문이 리턴한 정수를 파일기술자(file descriptor)라고 하며 프로그램에서 open된 파일을 액세스할 때 이 파일기술자를 사용 파일기술자는 descriptor table의 index 번호인데 descriptor table이란 현재 open되어 있는 파일의 각종 정보를 포함하고 있는 구조체를 가리키는 포인터들로 구성된 테이블이다.

4 프로그램에서 소켓을 개설하면 파일기술자와 똑같은 기능을 하는 소켓기술자(socket descriptor)가 리턴
응용 프로그램에서 이 소켓을 통하여 목적지 호스트와 연결을 요구하거나 패킷을 송수신할 때 해당 소켓기술자를 사용 UNIX에서는 파일기술자와 소켓기술자가 같은 기술자 테이블의 index가 된다. 즉, 파일과 소켓이 기술자 테이블을 공유한다. 한편 소켓번호는 응용 프로그램내에서 순서대로 배정되며 그 프로그램내에서만 유일하게 구분되면 되는 것이므로 서로 다른 응용 프로그램에서 같은 소켓번호를 사용하는 것은 무방 포트번호는 TCP/IP가 지원하는 상위 계층의 프로세스를 구분하기 위한 번호이므로 하나의 컴퓨터내에 있는 응용 프로세스들은 반드시 서로 다른 포트번호를 사용

5

6 비연결형: UDP--> 데이타그램 소켓
소켓의 이용 소켓을 이용한 네트웍 응용 프로그램에서 상대방과 IP 패킷을 주고받기 위하여는 다음의 다섯 가지 정보가 정해져야 한다. 통신에 사용할 프로토콜(TCP 또는 UDP) 자신의 IP 주소 자신의 포트번호 상대방의 IP 주소 상대방의 포트번호 통신에 사용할 프로토콜 연결형 : TCP--> 스트림 소켓 비연결형: UDP--> 데이타그램 소켓

7 /**** 파일명 : open_socket.c
컴파일 : cc -o open_socket open_socket.c -lsocket 실행예 : open_socket ****/ #include <stdio.h> /* 표준 입출력 함수 */ #include <sys/types.h> /* 소켓 시스템 콜에 필요한 상수 선언 */ #include <sys/stat.h> /* 파일의 상태에 대한 데이터 선언 */ #include <fcntl.h> /* 파일 제어 함수 선언 */ #include <sys/socket.h>/* 소켓 시스템콜 선언 */ int main() { /* 파일 및 소켓번호 */ int fd1, fd2, sd1, sd2 ; /* 파일 열기 */ fd1 = open("/etc/passwd", O_RDONLY, 0) ; printf("/etc/passwd's file descriptor = %d\n", fd1) ;

8 /* 스트림형 소켓 열기 */ sd1 = socket(PF_INET, SOCK_STREAM, 0) ; printf("stream socket descriptor = %d\n", sd1) ; /* 데이터그램형 소켓 열기 */ sd2 = socket(PF_INET, SOCK_DGRAM, 0) ; printf("datagram socket descriptor = %d\n", sd2) ; /* 또다른 파일 열기 */ fd2 = open("/etc/hosts", O_RDONLY, 0) ; printf("/etc/hosts's file descriptor = %d\n", fd2) ; /* 파일 및 소켓 닫기 */ close(fd2) ; close(fd1) ; close(sd2) ; close(sd1) ; }

9 위의 예제 open_socket.c의 실행 결과
/etc/passwd's file descriptor = 3 stream socket descriptor = 4 datagram socket descriptor = 5 /etc/hosts's file descriptor = 6

10 소켓 프로그래밍 절차 비연결형: [그림 8.4] 연결형: [그림 8.5]

11 RPC

12 자바 네트웍 프로그래밍 /*알기쉽게 해설한 Java -김충석 저- 참조 */
1. 네트워킹의 개요와 java.net 패키지 2. 인터넷 주소와 URL 3. TCP 소켓 4. UDP 소켓

13 1. 네트워킹의 개요와 java.net 패키지 자바는 사용자가 네트웍의 세부 구조를 모르고도 네트웍 기능을 편리하게 사용할 수 있는 기능들을 java.net 패키지로 제공 사용자는 java.net 패키지에서 제공되는 클래스들을 이용하여 네트워킹 관련 프로그램을 작성

14 1. 네트워킹의 개요와 java.net 패키지 TCP/IP(Transmission Control Protocol / Internet Protocol) 프로토콜 : 네트웍으로 연동되기 위해 상호 연동방법을 정의한 규약 인터넷의 표준 프로토콜 4개의 기능 계층으로 구성 : 대부분의 통신 응응 프로그램들은 응용 계층에서 사용 응용 계층 (HTTP, FTP, TELNET 등) 전달계층 (TCP, UDP 등) 인터넷 계층 (IP등) 네트워크 인터페이스 계층 (device driver 등) 하드웨어

15 1. 네트워킹의 개요와 java.net 패키지 TCP와 UDP 전달계층은 크게 TCP와 UDP로 구분된다
패킷(packet) 단위로 전송 TCP 연결성 통신 방식(전화) 신뢰성 보장 TELNET, HTTP, FTP 등 UDP 비연결성 통신 방식(편지) 모든 패킷이 목적지의 주소를 가진다 신뢰성이 낮다 TCP 보다 네트웍 부하가 덜하다 PING 등

16 1. 네트워킹의 개요와 java.net 패키지 소켓(socket) 컴퓨터가 연결된 컴퓨터의 끝점(전기의 소켓과 유사한 개념)
정보 송신 : 소켓에 보낼 정보를 Write 정보 수신 : 소켓으로부터 정보를 Read TCP/IP 소켓 TCP 소켓 UDP 소켓 포트(port) 하나의 컴퓨터에서 다수개의 네트웍 관련 프로그램을 서로 다른 포트를 사용하여 동시에 실행시킬 수 있다(실제 네트웍 라인은 하나) 논리적인 개념 포트 번호로 16비트 사용 예 : :8088

17 1. 네트워킹의 개요와 java.net 패키지 Java.net 패키지 ContenHandler DatagramPacket
DatagramSocket MulticastSocket DatagramSocketImpl InetAddress Object SeverSocket Socket SocketImpl URL URLConnection HttpURLConnection URLEncoder URLStreamHandler

18 2. 인터넷 주소와 URL- (1) InetAddress 클래스
인터넷 주소와 관련된 기능을 제공하는 클래스 주요 메소드 boolean equals(InetAddress other) 현 객체가 other 객체와 같은 주소를 가지면 true, 아니면 false를 반환 byte[] getAddress() 주소를 나타내는 4개의 요소를 가진 바이트 배열을 반환 String getHostAddress() 주소 정보를 나타내는 문자열을 반환 String getHostName() 컴퓨터 이름을 나타내는 문자열을 반환 InetAddress getLocalHost() 현재 컴퓨터를 나타내는 InetAddress 객체를 throws UnknownHostException 반환 InetAddress getByName(String hostName으로 지정된 컴퓨터를 나타 hostName) throws UnknownHostException 내는 InetAddress 객체를 반환 InetAddress[] getAllByName(String hostName) hostName으로 지정된 모든 컴퓨터(하 throws UnknownHostException 나의 도메인 이름으로 여러 대의 컴 퓨터를 사용하는 경우)를 나타내는 InetAddress 객체들의 배열을 반환

19 2. 인터넷 주소와 URL- (1) InetAddress 클래스
import java.net.*; class AddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println("로컬 컴퓨터의 이름 :" +Address.getHostName()); System.out.println("로컬 컴퓨터의 IP 주소:"+Address.getHostAddress()); Address = InetAddress.getByName("kowon.dongseo.ac.kr"); System.out.println("kowon.dongseo.ac.kr의 컴퓨터 이름과 IP주소 :" + Address.getHostAddress()); System.out.println("Adam.dongseo.ac.kr의 컴퓨터 이름과 IP주소 :"); InetAddress SW[] = InetAddress.getAllByName("adam.dongseo.ac.kr"); for(int i =0 ; i<SW.length; i++) System.out.println(SW[i]); }

20 실행결과 로컬 컴퓨터의 이름 :limpc 로컬 컴퓨터의 IP 주소 :203.241.179.45
kowon.dongseo.ac.kr의 컴퓨터 이름과 IP주소 : Adam.dongseo.ac.kr의 컴퓨터 이름과 IP주소 : adam.dongseo.ac.kr/

21 2. 인터넷 주소와 URL- (2) URL 클래스 WWW에서 사용하는 URL에 관한 정보를 제공 생성자
URL(String protocol, String host, int port, String file) throws MalformedURLException URL(String protocol, String host, String file) throws MalformedURLException URL(String urlString) throws MalformedURLException protocol, host, port, file : URL의 구성요소 urlString : URL의 모든 요소를 하나의 문자열로 표현한 것

22 2. 인터넷 주소와 URL- (2) URL 클래스 주요 메소드 String getFile() URL의 파일 이름을 반환
String getHost() URL의 호스트 이름을 반환 String getPort() URL의 포트 번호를 반환 String getProtocol() URL의 프로토콜 이름을 반환 String toExternalForm() 전체 URL의 문자열 객체를 반환 InputStream openStream() 지정된 URL로부터 정보를 읽어들이기 throws IOException 위한 객체를 반환 URLConnection openConnection() 지정된 URL과 연결후 URLConnection throws IOException 객체를 반환

23 2. 인터넷 주소와 URL- (2) URL 클래스 예제 import java.net.*; class htLimURL{
public static void main(String args[]) throws MalformedURLException { URL htLim = new URL(" System.out.println("프로토콜 : " + htLim.getProtocol()); System.out.println("포트 : " + htLim.getPort()); System.out.println("호스트 : " + htLim.getHost()); System.out.println("파일(경로포함) : " + htLim.getFile()); System.out.println("전체 URL : " + htLim.toExternalForm()); }

24 실행결과 프로토콜 : http 포트 : -1 호스트 : adam.dongseo.ac.kr
파일(경로포함) : /~htLim/comnet/test.html 전체 URL :

25 2. 인터넷 주소와 URL- (3) URLConnection 클래스
네트웍으로 연결된 원격지 컴퓨터의 자원을 알아내는 기능을 제공하는 클래스 주요 메소드 int getContentLength() 해당 문서의 길이를 바이트 수로 반환 String getContentType() 해당 문서의 타입을 반환 long getDate() 해당 문서의 생성 날짜를 반환 long getExpiration() 해당 문서의 파기 날짜를 반환 long getLastModified() 해당 문서의 마지막 수정 날짜를 반환 InputStream getInputStream() 원격지로부터 정보를 읽어 들이기 위한 throws IOException InputStream 객체를 생성하여 반환

26 2. 인터넷 주소와 URL- (3) URLConnection 클래스
원격지 자원을 가져오는 순서 1) 연결을 원하는 컴퓨터의 정보를 가진 URL 객체 생성 2) OpenConnection() 메소드를 이용하여 URLConnection 객체 생성 3) URLConnection 객체를 이용하여 속성을 알아낸다 4) URLConnection 클래스의 getInputStream() 메소드나 URL 클래스의 openStream() 메소드를 이용하여 원격지로부터 정보를 읽기 위한 InputStream 객체를 생성 . URL 클래스의 openStream() 메소드를 사용하는 경우 이 메소드는 자동으로 URL 클래스의 OpenConnection() 메소드를 호출한 다음 openStream() 메소드를 수행 5) InputStream 객체를 이용하여 원격지의 정보를 Read

27 2. 인터넷 주소와 URL- (3) URLConnection 클래스
import java.io.*; import java.util.Date; import java.net.*; class htLimURLConnection{ public static void main(String args[]) throws Exception { int c; URL htLim = new URL(" URLConnection htLimCon = htLim.openConnection();

28 System.out.println("문서의 타입 : " + htLimCon.getContentType());
System.out.println("마지막 수정 일자: " + new Date(htLimCon.getLastModified())); int len = htLimCon.getContentLength(); System.out.println("문서의 길이 : " + len + "바이트"); if(len>0){ System.out.println("================문서의 내용=============="); InputStream input = htLimCon.getInputStream(); int i = len; while(((c = input.read()) != -1) && (--i > 0)){ System.out.print((char) c); } input.close(); }else { System.out.println("내용이 없음");

29 실행결과 문서의 타입 : text/html 마지막 수정 일자: Mon Jun 07 16:44:56 GMT+09:00 1999
문서의 길이 : 4572바이트 ================문서의 내용============== <HTML> <HEAD> -- 이하 생략-- </BODY>

30 3. TCP 소켓 자바는 TCP 기반의 클라이언트-서버 통신을 위해 ServerSocket, Socket 클래스를 제공
클라이언트-서버 환경에서의 서버측 프로그램은 데몬 프로그램처럼 실행 상태로 클라이언트의 요청을 기다린다 ServerSocket 클래스 생성자 ServerSocket(int port) throws IOException) port : 클라이언트의 요청을 받아들일 포트 번호 메소드 Socket accept() throws IOException 클라이언트의 요청을 받아들인 다음, Socket 클래스 객체를 반환 void close() throws IOException 서버 소켓을 닫는다

31 3. TCP 소켓 Socket 클래스 : 클라이언트와 서버 사이의 실질적인 정보 교환 생성자
Socket(String hostName, int port) throws UnknownHostException, IOException hostName : 연결을 원하는 컴퓨터의 주소(예: 또는 sslab.daehan. ac.kr) port : 연결할 포트 번호

32 3. TCP 소켓 Socket 클래스의 주요 메소드
InputStream getInputStream() 현재의 소켓과 관련된 InputStream 객체를 반환 throws IOException OutputStream getOutputStream() 현재의 소켓과 관련된 OutputStream 객체를 반환 throws IOException void close() throws IOException 소켓을 닫는다 InetAddress getInetAddress() 현재 소켓에 연결된 컴퓨터의 주소를 반환 InetAddress getLocalAddress() 현재 소켓을 사용하고 있는 컴퓨터의 주소를 반환 int getPort() 현재 소켓에 연결된 컴퓨터의 포트 번호를 반환 int getLocalPort() 현재 소켓이 사용하고 있는 포트 번호를 반환

33 3. TCP 소켓 TCP 소켓의 동작 accept() 네트웍 네트웍 ServerSocket
서버 클라이언트 클라이언트 서버 accept() Socket ServerSocket Socket new Socket

34 3. TCP 소켓 클라이언트-서버의 동작 순서 서버측
1) ServerSocket 클래스를 이용하여 서버 소켓 객체를 생성한 다음 클라이언트의 요청을 기다린다 2) 클라이언트의 요청이 발생되면 요청을 받아들여 Socket 객체를 생성 3) Socket 객체를 이용하여 입출력을 위한 스트림을 생성 4) 통신을 수행 5) 소켓을 닫는다 클라이언트 측 1) 연결을 원하는 서버의 주소와 포트 번호로 Socket 객체를 생성 2) Socket 객체를 이용하여 입출력을 위한 스트림을 생성 3) 통신을 수행 4) 소켓을 닫는다

35 3. TCP 소켓 import java.io.*; import java.net.*; class ServerSide {
public static void main(String args[]) { try { int port = Integer.parseInt(args[0]); ServerSocket ss = new ServerSocket(port); while(true) { Socket s = ss.accept(); OutputStream os = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); for(int i=1;i<=10;i++) dos.writeInt(i); s.close(); } catch(Exception e) { System.out.println("Exception: " + e); } } }

36 import java.io.*; import java.net.*; class ClientSide { public static void main(String args[]) { try { String server = args[0]; int port = Integer.parseInt(args[1]); Socket c = new Socket(server, port); InputStream is = c.getInputStream(); DataInputStream dis = new DataInputStream(is); for(int i=1; i<=10; i++) { int j = dis.readInt(); System.out.println("서버로부터 받은 테이터 " + j + " 출력"); } c.close(); catch(Exception e) { System.out.println("Exception: " + e); } }

37 실행절차 실행결과 >java ServierSide 1111 >java ClientSide 127.0.0.1 1111
서버로부터 받은 데이터 1 출력 서버로부터 받은 데이터 2 출력 서버로부터 받은 데이터 3 출력 서버로부터 받은 데이터 9 출력 서버로부터 받은 데이터 10 출력

38 4. UDP 소켓 UDP(User Datagram Protocol) 비연결성 통신 방식
높은 신뢰성이 요구되지 않는 분야에 이용 TCP에 비해 네트웍에 부담을 주지 않는다 자바는 UDP를 지원하기 위해 DatagramPacket, DatagramSocket 클래스 제공

39 4. UDP 소켓 DatagramPacket 클래스 정보를 주고 받기 위한 준비과정의 기능을 제공하는 클래스 생성자
DatagramPacket(byte[] buffer, int size) : 데이터를 수신하는 응용 프로그램에서 사용하는 생성자 buffer : 수신되는 데이터를 저장할 바이트 배열 size : 배열의 크기 DatagramPacket(byte[] buffer, int size, InetAddress ia, int port) : 데이터를 송신하는 응용프로그램에서 사용하는 생성자 buffer : 송신될 데이터가 저장되어 있는 배열 ia : 정보가 보내질 컴퓨터의 주소이며 InetAddress 객체를 사용하여 지정 port : 컴퓨터의 포트 번호

40 4. UDP 소켓 DatagramPacket 클래스의 주요 메소드
InetAddress getAddress() 수신 응용 프로그램에서 사용한다 정보를 보낸 컴퓨터의 주소를 반환 byte[] getData() 패킷으로부터 데이터를 읽어 들여 바이트 배열로 반환 int getLength() 패킷의 바이트 수를 반환 int getPort() 포트번호를 반환 void setAddress(InetAddress ia) ia를 주소로 설정 void setData(byte buffer[]) buffer의 내용을 패킷의 데이터로 설정 void setLength(int size) 패킷의 크기를 size로 설정 void setPort(int pt) 포트번호를 pt 값으로 설정

41 4. UDP 소켓 DatagramSocket 클래스 실제 정보를 주고 받는 기능을 제공하는 클래스 생성자
DatagramSocket() throws SocketException DatagramSocket(int port) throws SocketException port : 소켓이 사용할 포트 번호 주요 메소드 void receive(DatagramPacket dgram) 현재의 소켓으로부터 정보를 읽어 throws IOException dgram 패킷에 저장 void send(DatagramPacket dgram) 현재의 소켓을 통하여 dgram throws IOException 패킷을 전송 void close() throws IOException 소켓을 닫는다

42 4. UDP 소켓 import java.net.*; class UDPReceiver {
private final static int BUFSIZE = 30; public static void main(String args[]) { try { int port = Integer.parseInt(args[0]); DatagramSocket ds = new DatagramSocket(port); while(true) { byte buffer[] = new byte[BUFSIZE]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); ds.receive(dp); String str = new String(dp.getData()); System.out.println("수신된 테이터 : " + str); } catch(Exception e) { e.printStackTrace(); } }

43 import java.net.*; class UDPSender { public static void main(String args[]) { try { DatagramSocket ds = new DatagramSocket(); InetAddress ia = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); byte buffer[] = args[2].getBytes(); DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, port); ds.send(dp); } catch(Exception e) { e.printStackTrace();

44 실행절차 실행결과 >java UDPReceiver 1234
>java UDPSender 자바는쉽다 실행결과 수신된 데이터 : 자바는쉽다

45 Intro. To Java Programming
Objectives Describes the key features of the Java language Describe the Java Virtual Machine Write a simple Java application, compile and run it. Use the Java API on-line documentation

46 What is Java? A programming language A development environment
An application environment Key features Object-oriented language Provide an interpreted environment Eliminate pointer arithmetic and memory allocation/deallocation Possible to run more than one thread Improved security

47 Java Virtual Machine(JVM)
An imaginary machine that is implemented by software Provide the hardware platform specification to which all Java code is compiled. Enables Java programs to be platform independent It is up to the Java interpreter of each specific hardware platform to ensure the running of code compiled for the JVM.

48 Java Translation and Execution
Java source code Java bytecode Java compiler Java interpreter Bytecode compiler Runtime Machine code

49 Java Translation and Execution
The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java is considered to be architecture-neutral

50 Java Program Structure
See HelloWorldApp.java A program is made up of one or more classes A class contains one or more methods A method contains program statements A Java application always executes the main method

51 Java program 예: HelloWorldApp.java
// // Sample HelloWorld application public class HelloWorldApp{ public static void main (String args[]) { System.out.println ("Hello World!"); }

52 Java Translation and Execution
Executing the compiler in a command line environment: > javac HelloWorldApp.java This creates a file called HelloWorldApp.class, which is submitted to the interpreter to be executed: > java HelloWorldApp The .java extension is used at compile time, but the .class extension is not used with the interpreter Other environments do this processing in a different way

53 Errors A program can have three types of errors
The compiler will find problems with syntax and other basic issues (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results (logical errors)

54 Using the java Documentation
The layout of this documentation is hierarchical.---> inheritance property Each class document has the same format The main sections of a class document include: The class hierarchy A description of the class and its general purpose A list of member variables A list of constructors A list of methods A detailed list of variables, constructors, methods

55 The Java API The Java Application Programmer Interface (API) is a collection of classes that can be used as needed The println and print methods are part of the Java API. Both methods print information to the screen; the difference is that println moves to the next line when done, but print does not

56 Class Libraries The Java API is a class library, a group of classes that support program development Classes in a class hierarchy are often related by inheritance The classes in the Java API is separated into packages The System class, for example, is in package java.lang Each package contains a set of classes that relate in some way

57 The Java API Packages Some packages in the Java API: java.applet
java.awt java.beans java.io java.lang java.math java.net java.rmi java.security java.sql java.text java.util

58 Importing Packages Using a class from the Java API can be accomplished by using its fully qualified name: java.lang.System.out.println (); Or, the package can be imported using an import statement, which has two forms: import java.applet.*; import java.util.Random; The java.lang package is automatically imported into every Java program

59 Java Applets A Java applet is a Java program that is intended to be sent across a network and executed using a Web browser A Java application is a stand alone program Applications have a main method, but applets do not Applets are derived from the java.applet.Applet class Links to applets can be embedded in HTML documents

60 Java Applets local computer Java source code Java compiler Java
bytecode Web browser remote computer Java interpreter


Download ppt "8장. 네트워크 프로그래밍 /*컴퓨터 네트워크 프로그래밍 -김화종 저- 참조 */"

Similar presentations


Ads by Google