Socket의 UDP 통신 예

UDP 통신 방식:
1, 클라이언트는 연결할 필요가 없고 서버에 직접 접근하여sendto를 통해 데이터를 보내고recvfrom는 데이터를 받아들인다
2, 서비스 측은 클라이언트의 요청을 감청하고 받아들일 필요가 없다. 클라이언트 socket이sendto를 통해 클라이언트의 요청에 응답할 때.
클라이언트 측:
#include 
#include 

#pragma comment(lib, "WS2_32.lib")
const unsigned int PORT = 11024;
const int kBufferSize	= 1024;

int main() {

	WSADATA wsData;
	if(WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
		std::cout << "start up failed
" << std::endl; return 0; } // connect the socket; SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); SOCKADDR_IN addIn; addIn.sin_family = AF_INET; addIn.sin_port = htons(PORT); addIn.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); char cSendBuffer[kBufferSize] = "Client sends a Message to the Server, please confirm?"; int bRecvLen = sizeof(addIn); int bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn)); while(bSendRet != SOCKET_ERROR) { char cRecvBuffer[kBufferSize] = "#"; int bRecv = recvfrom(s, cRecvBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, &bRecvLen); if(bRecv != SOCKET_ERROR) { std::cout << "Client recvie the infromation from the server is: " << cRecvBuffer << std::endl; ZeroMemory(cSendBuffer, kBufferSize); std::cout << "please input the information the sends to the server: "; std::cin >> cSendBuffer; bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn)); } else{ break; } } if(WSACleanup() != 0) { std::cout << "clean up failed
"; return -1; } closesocket(s); return 0; }

서버 측:
#include 
#include 

#pragma comment(lib, "WS2_32.lib")

const unsigned int PORT = 11024;
const int kBufferSize	= 1024;

int main() {
	WSADATA wsData;
	if(WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
		std::cout << "start failed" << std::endl;
		return -1;
	}
	//
	SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	SOCKADDR_IN addIn;
	
	addIn.sin_family = AF_INET;
	addIn.sin_port = htons(PORT);
	addIn.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	int bBindRet = bind(s, (LPSOCKADDR) &addIn, sizeof(addIn));
	if(bBindRet != 0) {
		std::cout << "bind failed" << std::endl;
		return -1;
	}

	char cRecvBuffer[kBufferSize];
	int ilen = sizeof(addIn);				
	int iRecv = recvfrom(s, cRecvBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, &ilen);
	while(iRecv != SOCKET_ERROR) {
		std::cout << "recvie information: " << std::endl;
		char cSendBuffer[kBufferSize];
		std::cout << "Input the information that the client sends; " << std::endl;
		std::cin >> cSendBuffer;
		sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
	}

	if(WSACleanup() != 0) {
		std::cout << "Clean up failed" << std::endl;
		return -1;
	}

	return 0;
}

좋은 웹페이지 즐겨찾기