가장 간단한 UDP 통신

여기에 붙이는 것은 주로 테스트 코드를 만들 때 직접 여기에서 복사하여 한 줄을 절약하여 쓰는 것이다
서버:
#include "stdafx.h"
#include "stdio.h"  
#include "Winsock2.h"  
#include "iostream"  
#include "string"  
#pragma comment(lib,"WS2_32.lib")

#define OK_STR "OK"  

void main()
{
	int version_a = 1;
	int version_b = 1;
	WORD versionRequest = MAKEWORD(version_a, version_b);
	WSAData wsaData;
	int err = WSAStartup(versionRequest, &wsaData);

	if (err != 0)
	{
		printf("ERROR!");
		return;
	}

	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
	{
		printf("WRONG WINSOCK VERSION!");
		WSACleanup();
		return;
	}

	SOCKET socServer = socket(AF_INET, SOCK_DGRAM, 0);

	SOCKADDR_IN addr_Srv;
	addr_Srv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	addr_Srv.sin_family = AF_INET;
	addr_Srv.sin_port = htons(28080);
	bind(socServer, (SOCKADDR*)&addr_Srv, sizeof(SOCKADDR));

	SOCKADDR_IN addr_Clt;
	char recvBuf[100];
	int fromlen = sizeof(SOCKADDR);

	while (true)
	{
		recvfrom(socServer, recvBuf, 100, 0, (SOCKADDR*)&addr_Clt, &fromlen);
		std::cout << recvBuf << ":" << addr_Clt.sin_port << std::endl;
		sendto(socServer, OK_STR, strlen(OK_STR) + 1, 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));
	}
	closesocket(socServer);
	WSACleanup();
}

클라이언트:
#include "stdafx.h"
#include "Winsock2.h"  
#include "iostream"  
#include "stdio.h"  
#pragma comment(lib, "ws2_32.lib")  

void main()
{

	int version_a = 1;
	int version_b = 1;
	WORD versionRequest = MAKEWORD(version_a, version_b);
	WSAData wsaData;
	int error = WSAStartup(versionRequest, &wsaData);

	if (error != 0)
	{
		printf("ERROR!");
		return;
	}
	if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
	{
		printf("WRONG WINSOCK VERSION!");
		WSACleanup();
		return;
	}


	char requestStr[100];
	SOCKET socClient = socket(AF_INET, SOCK_DGRAM, 0);
	SOCKADDR_IN addrSrv;  
	addrSrv.sin_addr.S_un.S_addr = inet_addr("47.94.155.26");//47.94.155.26192.168.1.117
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(28080);

	char cRecvBuf[100];
	while (true)
	{
		std::cin >> requestStr;
		sendto(socClient, requestStr, strlen(requestStr) + 1, 0, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)); 
		recv(socClient, cRecvBuf, strlen(cRecvBuf) + 1, 0);
		std::cout << cRecvBuf << std::endl;
	}

	closesocket(socClient);
	WSACleanup();

	//  return 0;  
}

좋은 웹페이지 즐겨찾기