lecture2_2.0

advertisement
Network Socket
Programming
Contents
 SOCKET
API
 TCP/IP
 MFC
Programming Overview
Appendix C
SOCKETS:
A Programmers Introduction
The concept


Sockets and sockets programming was developed in
the 1980s
A socket

enables communication between a client and server process



connection-oriented or connectionless
Can be considered an endpoint in a communication
Once the appropriate sockets are engaged, the two
computers can exchange data.
The Berkeley Socket Interface


The de facto standard application programming
interface (API)
Provides a library of functions



Generic access to inter-process communications services
Programmers can use to develop network aware application
Functionality of




identifying endpoints of the connection
Establishing the communication
Allowing messages to be sent, waiting for incoming
messages
Terminating the communication, and error handling.
Most widely used socket interfaces

The Berkley Software Distribution Sockets
(BSD)
 Introduced

for UNIX
Windows Sockets API from Microsoft
 Slight
modification of BSD
The Requirements

This Socket material is intended for the C language
programmer.



It provides external references for the C++, Visual Basic, and
PASCAL languages.
Basic knowledge of the TCP/IP and UDP network
protocols is assumed.
The language has to recognize dynamic link libraries
(DLLs)

In a 32-bit Windows environment, import the wsock32.lib to
take advantage of the WinSock API.



When library has to be linked (when create executables.)
Wsock32.dll gets loaded
Wsock32.dll runs over the TCP/IP stack. (implicitly link at
runtime.)
The Client/Server Model of Communication

The basic model of stream-based (or TCP/IP sockets)
communication
Diagram of Stream Socket Communication
The Client/Server Model of Communication
Flowchart of Datagram Socket Communication
TCP/IP
Internet 통신

Protocol


통신하고자 하는 컴퓨터들 사이에 미리 정해 둔 규약
 접속방법, 데이터 송신방법, 주소 체계 등을 포함
OSI Reference Model

통신을 위한 복잡한 여러 기능들을 조직적으로 분류하여 이를 7
개의 계층으로 분리하여 계층별로 프로토콜을 제정, 관리할 수
있도록 한 표준
Application
Presentation
Session
Transport
Network
Data link
Physical
OSI 7 계층
TCP/IP

TCP/IP
인터넷의 효시인 ARPARNET의 protocol로 개발되었다
 TCP는 종단간의 신뢰성 있는 전송을 담당, IP는 인터넷상에서의
routing과 전달을 담당

User Data
TCP
Header
IP
Header
Network
Header
Application
Byte Stream
TCP
Segment
IP
Datagram
Network-level
packet
TCP/IP
Application layer
Application layer
가상적인 통신
Transport layer
Transport layer
Internet layer
Internet layer
Physical layer
Physical layer
실제적인 통신
Socket

Socket:
 TCP/IP
프로토콜을 이용하는 네트워크 프로그램을
개발하기 위한 인터페이스
 Application 프로그램은 socket을 이용하여 transport
layer 이하의 통신 기능을 이용할 수 있음
 IP 주소와 port 번호를 사용하여 통신
(Ex: 전화번호: IP, 통화하는 사람: Port number)
IP 주소
 IP
Address
 Internet상에
접속해 있는 컴퓨터들의 주소
 32bit-length in IP version 4
 166.104.88.92와 같이 8bits단위로 분리, 4 class
type으로 분류
 논리적 최대 주소 개수=256*256*256*256=42억 개
 주소 부족 현상의 대두 - IPv6에서는 128 bits로 규정
Port number

Port number

한 컴퓨터 안에서 수행될 수 있는 application program들을 구별하기
위해서 정해진 식별 번호


Internet Assigned Numbers Authority (IANA)
16bit-정수

1023 – registerd well known ports




ftp service : port 21, telnet 23, HTTP 80
1024~49151 – used to multiple purpose.
49152~65535 – used to dynamic and private port
주요 port 번호 (RFC790)






#define
#define
#define
#define
#define
#define
IPPROTO_IP
IPPROTO_ TCP
IPPROTO_ UDP
IPPORT_ NETSTAT
IPPORT_ FTP
IPPORT_ TELNET
0
6
12
15
21
23
MFC Programming Overview
MFC의 Class Library
Application Framework
CObject
거의 모든 MFC 클래스의 기반 클래스
CCMDTarget
커맨드 메시지를 받는 기능
CWinApp
프로그램을 구동시키는 기능
CDocument
데이터를 저장하고 처리하는 기능
CWnd
윈도우에 관련된 기능(눈에 보이는 오브젝트)
CFrameWnd
프로그램 윈도우 프레임(외곽)을 관리
CView
데이터를 보여주는 윈도우 관리
MFC 기반 클래스
Application Framework
파생 클래스
CObject
CCMDTarget
CWinApp
CMyApp
CDocument
CMyDoc
CWnd
CFrameWnd
CMainFrame
CView
CMyView
MFC 기반 클래스
CWinApp 클래스

프로그램을 구동시
켜 주는 기능



프로그램 시작과 종료를
담당
프로그램 시작될 때, 메
인 프레임 윈도우를 생성
무한루프를 돌면서 메시
지를 뿌려준다
(WM_QUIT 메시지를 만
나면 무한루프를 빠져나
옴)
CWnd 클래스


CWnd 클래스는 화면에 출력되
어 우리 눈에 보이는 윈도우라
는 오브젝트를 클래스로 구현
CWnd은 2가지 부류의 약 300
여 개의 멤버함수를 갖는다.


윈도우의 크기, 위치, 모양, 상
태 등을 제어하기 위한 기능을
제공 => CFrameWnd 클래스
의 기능
메시지 핸들러라 불리는 멤버
함수, 윈도우에서 발생하는 메
시지를 처리하기 위한 함수
=>CView 클래스 기능
메시지 핸들러 함수



메시지 핸들러 함수는 윈도우에서 발생하는 메시지를
처리하기 위한 함수
Overriding해서 사용하지만 가상함수는 아님
메시지 맵을 사용하여 가상함수처럼 Overriding 할 수
있음

메시지 맵은 일종의 매크로이며, 파생클래스의 메시지 핸들러 함
수를 여기에 등록을 하면 기반 클래스의 함수를 무시하고 파생
클래스의 함수를 호출해 줌 =>자동으로 등록시켜줌
CView/CDocument 클래스

CView 클래스



프로그램에서 다루는 데이터를 보여주는 일을 함
GetDocument라는 멤버함수는 도큐먼트 오브젝트의 포인터
를 얻는 함수, 이것으로 도큐먼트에 저장되어 있는 데이터를
가져옴
CDocument 클래스

프로그램에서 처리하는 데이터를 저장하고, 읽어오고, 처리
하는 기능





파일로부터 데이터를 읽어오는 기능(“파일”메뉴의”열기” 기능)
파일에 데이터를 저장하는 기능(“파일”메뉴의”저장”기능)
새로운 데이터를 만드는 기능(“파일”메뉴의”새 파일”기능)
작업 중인 데이터를 닫는 기능(“파일”메뉴의”닫기”기능)
데이터가 변경된 사실을 뷰 오브젝트에 알리는 기능
CView/CDocument 클래스

GetDocument 함수

CView::GetDocument


CDocument* GetDocument() const;
Return Value
현재 view 와 관련된 CDocument object를 가리키는 포인
터가 반환된다. 만약 view에 관련된 document가 없다면
NULL이 반환된다.
Remark
view의 document에 대한 포인터를 반환한다. 반환된 포인
터를 사용하여 document의 멤버 함수 호출이 가능해진다.
CView/CDocument 클래스

OnDraw 함수

CView::OnDraw


virtual void OnDraw ( CDC* pDC ) = 0 ;
Parameter
pDC는 document의 image를 rendering 하는데 사용되는
device context를 가리킨다.
Remark
document의 image를 rendering 하기 위해 framework에
의해 호출된다. framework는 screen display, printing,
print preview 등을 위해 이 함수를 호출한다.
CView/CDocument 클래스

예) AppWizard에 의해 생성된 ExView.cpp 소스 파일의 내부에는 OnDraw
함수가 선언되어 있다고 할 때
void CExView::OnDraw(CDC* pDC)
{
CExDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}

// TODO: add draw code for native data here
여기서 ASSERT_VALID(pDoc);는 pDoc가 활성화 되어있는 것인가를 검증하
는 것이다. 여기에 다음과 같은 코드를 적어 넣으면 문자가 주어진 좌표에 표시
된다.

void CExView::OnDraw(CDC* pDC)
{
CExDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
}
pDC->TextOut(0,0,"Hello !! Control & System !",27);
// TODO: add draw code for native data here
CView/CDocument 클래스

GetDocument 함수는 CExDoc 형의 포인터인 pDoc로 값을 리턴
하고 사용 가능한지 확인한다. 그 후 pDC, 즉 Device Context의 멤
버 함 수 인 TextOut 함 수 로 문 자 열 을 출 력 한 다 .

여기서 출력 문자열에 대한 정보가 전 페이지 경우처럼 직접 나올
수도 있고 CExDoc에서 올수도 있다. 이때 pDoc로 그 자료들을 가
리켜 주어야 한다.

또한 화면에 무엇이든지 그릴때, 출력할때는 CDC 클래스의 여러
멤 버 함 수 를 사 용 한 다 . 한 가 지 더 참 고 로 OnDraw 함 수 는
InvalidateRect 함수가 호출될때에도 따라서 호출된다.
Note & Q/A

강의 일정





프로젝트 제안서 제출


1주: OOP Concept, C++ 개요
2주: SOCKET API, TCP/IP, MFC Programming Overview
3주: Network 접속, MFC 소켓 클래스, 범용 소켓 소개
4주: 예제 서버, 클라이언트 채팅 소스 분석 및 관련 API
Overview
중간고사기간 이후 공고
프로젝트 최종 보고서 제출 및 최종 결과물 시연 평가

날짜: 2010년 12월 초/중

오후 6시경 컴퓨터실(예정, 차후공고)
Download