📣 전송 제어 프로토콜 (TCP, Transmission Control Protocol, SOCK_STREAM)
전송 제어 프로토콜(Transmission Control Protocol, TCP, 문화어: 전송 조종 규약)은 인터넷 프로토콜 스위트(IP)의 핵심 프로토콜 중 하나로, IP와 함께 TCP/IP라는 명칭으로도 널리 불린다. TCP는 근거리 통신망이나 인트라넷, 인터넷에 연결된 컴퓨터에서 실행되는 프로그램 간에 일련의 옥텟을 안정적으로, 순서대로, 에러 없이 교환할 수 있게 한다. TCP는 전송 계층에 위치한다. 네트워크의 정보 전달을 통제하는 프로토콜이자 인터넷을 이루는 핵심 프로토콜의 하나로서 국제 인터넷 표준화 기구(IETF)의 RFC 793에 기술되어 있다.
📌 Connection Establishment (3 Way handshaking) | 📌 Connection Termination (4 Way handshaking) |
In telecommunications, a handshake is an automated process of negotiation between two communicating in between participants (example "Alice and Bob") through the exchange of information that establishes the protocols of a communication link at the start of the communication, before full communication begins. The handshaking process usually takes place in order to establish rules for communication when a computer attempts to communicate with another device. Signals are usually exchanged between two devices to establish a communication link. For example, when a computer communicates with another device such as a modem, the two devices will signal each other that they are switched on and ready to work, as well as to agree to which protocols are being used.
📌 전송 제어 프로토콜의 특징 (Transmission Control Protocol Features)
-
중간에 데이터가 소멸되지 않고 목적지로의 전송을 보장한다.
-
전송 순서대로 데이터가 수신된다.
-
전송되는 데이터의 경계 (Boundary)가 존재하지 않는다.
🔍 TCP/IP Server 함수호출 순서
1️⃣ Socket() - 소켓생성
-
The socket function creates a socket that is bound to a specific transport service provider.
📋 Socket() Syntax
SOCKET WSAAPI socket(
int af,
int type,
int protocol
);
📋 Socket() Source Code by C++
private:
int szClntAddr;
SOCKET hServSock;
SOCKADDR_IN servAddr;
/* ^---------HEADER---------^ */
// MARK: Create TCP Socket
this->hServSock = socket(PF_INET, SOCK_STREAM, 0);
if (this->hServSock == INVALID_SOCKET) {
// here error message.
}
2️⃣ Bind() - 소켓 주소할당
-
The bind function associates a local address with a socket.
📋 Bind() Syntax
int bind(
SOCKET s,
const sockaddr *addr,
int namelen
);
📋 Bind() Source Code by C++
std::memset(&this->servAddr, 0, sizeof(SOCKADDR_IN));
this->servAddr.sin_family = AF_INET;
this->servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // INADDR_ANY 모든 IP 대역 접속을 허가한다.
this->servAddr.sin_port = htons(port);
// MARK: bind 함수는 지역주소를 소켓과 함께 결합(연관)시킵니다.
if (bind(this->hServSock, (sockaddr *)&this->servAddr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) {
// here error message.
}
3️⃣ Listen() - 연결요청 대기상태
-
The listen function places a socket in a state in which it is listening for an incoming connection.
📋 Listen() Syntax
int WSAAPI listen(
SOCKET s,
int backlog
);
📋 Listen() Source Code by C++
// MARK: listen 함수는 소켓을 들어오는 연결에 대해 listening 상태에 배치합니다.
if (listen(this->hServSock, MAX_REQUEST_QUEUE_SIZE) == SOCKET_ERROR) {
// here error message.
}
4️⃣ Accept() - 연결허용
-
The accept function permits an incoming connection attempt on a socket.
📋 Accept() Syntax
SOCKET WSAAPI accept(
SOCKET s,
sockaddr *addr,
int *addrlen
);
📋 Accept() Source Code by C++
// MARK: Accpet 함수는 소켓에 들어오는 연결 시도에 대해서 허가한다.
SOCKADDR_IN clientAddr;
this->szClntAddr = sizeof(SOCKADDR_IN);
SOCKET hClientSock = accept(this->hServSock, (SOCKADDR *)&clientAddr, &this->szClntAddr);
if (hClientSock == INVALID_SOCKET || hClientSock == SOCKET_ERROR) {
// here error message and close sock.
}
5️⃣ Read()/Write() - 데이터 송수신
-
The recv function receives data from a connected socket or a bound connectionless socket.
-
The send function sends data on a connected socket.
📋 Read() / Write() Syntax
int WSAAPI send(
SOCKET s,
const char *buf,
int len,
int flags
);
int recv(
SOCKET s,
char *buf,
int len,
int flags
);
📋 Read() / Write() Source Code by C++
const bool OnSendMessage(const SOCKET sock, const std::string message) {
return send(sock, message.c_str(), message.size(), 0) == 0 ? true : false; // ZERO == Success, EOF == Fail
}
const int OnReceiveMessage(const SOCKET sock) {
char message[BUFSIZ];
const int length = recv(sock, message, BUFSIZ, 0);
return length;
}
6️⃣ Close() - 연결종료
-
The closesocket function closes an existing socket.
📋 Close() Syntax
int closesocket(
IN SOCKET s
);
📋 Close() Source Code by C++
closesocket(this->hServSock);
🔍 TCP/IP Client 함수호출 순서
1️⃣ Socket() - 소켓생성
-
The socket function creates a socket that is bound to a specific transport service provider.
📋 Socket() Syntax
SOCKET WSAAPI socket(
int af,
int type,
int protocol
);
📋 Socket() Source Code by C++
private:
SOCKET hServSock;
SOCKADDR_IN servAddr;
/* ^---------HEADER---------^ */
this->hServSock = socket(PF_INET, SOCK_STREAM, 0);
if (this->hServSock == INVALID_SOCKET) {
// here error message and close sock.
}
2️⃣ Connect() - 연결요청
-
The connect function establishes a connection to a specified socket.
📋 Connect() Syntax
int WSAAPI connect(
SOCKET s,
const sockaddr *name,
int namelen
);
📋 Connect() Source Code by C++
std::memset( &this->servAddr, 0, sizeof(SOCKADDR_IN) );
this->servAddr.sin_family = AF_INET; // IPv4
this->servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
this->servAddr.sin_port = htons(1234);
// MARK: 생성한 소켓을 통해 서버로 접속을 요청합니다.
if ( connect(this->hServSock, (SOCKADDR *)&servAddr, sizeof(SOCKADDR)) == SOCKET_FAIL_ERROR) {
// here error message and close sock.
}
3️⃣ Read()/Write() - 데이터 송수신
-
The recv function receives data from a connected socket or a bound connectionless socket.
-
The send function sends data on a connected socket.
📋 Read() / Write() Syntax
int WSAAPI send(
SOCKET s,
const char *buf,
int len,
int flags
);
int recv(
SOCKET s,
char *buf,
int len,
int flags
);
📋 Read() / Write() Source Code by C++
const bool OnSendMessage(const SOCKET sock, const std::string message) {
return send(sock, message.c_str(), message.size(), 0) == 0 ? true : false; // ZERO == Success, EOF == Fail
}
const int OnReceiveMessage(const SOCKET sock) {
char message[BUFSIZ];
const int length = recv(sock, message, BUFSIZ, 0);
return length;
}
4️⃣ Close() - 연결종료
-
The closesocket function closes an existing socket.
📋 Close() Syntax
int closesocket(
IN SOCKET s
);
📋 Close() Source Code by C++
closesocket(this->hServSock);
📂 Windows TCP/IP Source Code Files
🚀 REFERENCE
'#컴퓨터 과학 [Computer Science] > C/C++' 카테고리의 다른 글
[ObjectiveC] Objective-C 요약 (0) | 2022.03.31 |
---|---|
[C/C++] C++ 백터와 배열의 차이점 (C++ Vector and Array Difference) (0) | 2020.02.23 |
[C/C++] 시리얼 통신 (Serial Communication) (0) | 2019.09.04 |
[C/C++] INI (Initialization) 파일 (0) | 2019.08.22 |
C/C++ Computer Language (0) | 2019.05.06 |
댓글