windows UDP简单实例

直接上例子代码

client:

#include 
#include 

#pragma comment(lib,"ws2_32.lib")
#define	BUF_SIZE	1024
#define PORT_		9411

int main(void)
{
	WSADATA wsd;
	int iRet = 0;

	// 初始化套接字动态库
	if(WSAStartup(MAKEWORD(2,2), &wsd) != 0){
		iRet = WSAGetLastError();
		printf("WSAStartup failed !\n");
		return -1;
	}

	char strSend[BUF_SIZE] = "test udp send", strRecv[BUF_SIZE] = {0};
	SOCKADDR_IN servAddr;
	SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);

	// 设置服务器地址
	servAddr.sin_family = AF_INET;
	//servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.0.104");
	servAddr.sin_addr.S_un.S_addr = inet_addr("192.168.0.255");
	servAddr.sin_port = htons(PORT_);

	// 向服务器发送数据
	int nServAddLen = sizeof(servAddr);
	iRet = sendto(sockClient, strSend, BUF_SIZE, 0, (sockaddr *)&servAddr, nServAddLen);
	if(iRet == SOCKET_ERROR){
		printf("sendto() failed:%d\n", WSAGetLastError());
		closesocket(sockClient);
		WSACleanup();
		return -1;
	}

	iRet = recvfrom(sockClient, strRecv, BUF_SIZE, 0, (sockaddr *)&servAddr, &nServAddLen);
	if(SOCKET_ERROR == iRet) 
	{ 
		printf("recvfrom failed:%d\n", WSAGetLastError());
		closesocket(sockClient); 
		WSACleanup(); 
		return -1; 
	}

	printf("Recv From Server:%s\n", strRecv);
	closesocket(sockClient);
	WSACleanup();
	
	return 0;
}

server:

#include 
#include 

#pragma comment(lib,"ws2_32.lib")
#define	BUF_SIZE	1024
#define PORT_		9411

int main(void)
{
	WSADATA wsd;
	int iRet = 0;

	// 初始化套接字动态库
	if(WSAStartup(MAKEWORD(2,2), &wsd)!= 0){
		printf("WSAStartup failed:%d!\n", WSAGetLastError());
		return -1;
	}

	SOCKET socketSrv = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	SOCKADDR_IN addrSrv;
	SOCKADDR_IN addrClient;
	char strRecv[BUF_SIZE] = {0}, strSend[BUF_SIZE] = "udp server send";
	int len = sizeof(SOCKADDR);

	// 设置服务器地址
	ZeroMemory(strRecv,BUF_SIZE);
	//addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	addrSrv.sin_addr.S_un.S_addr = inet_addr("192.168.0.104");
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(PORT_);

	// 绑定套接字
	iRet = bind(socketSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
	if(SOCKET_ERROR == iRet)
	{ 
		printf("bind failed%d!\n", WSAGetLastError());
		closesocket(socketSrv);
		WSACleanup();
	}

	// 从客户端接收数据
	printf("udp server start...\n");
	while(TRUE)
	{
		iRet = recvfrom(socketSrv,strRecv,BUF_SIZE,0,(SOCKADDR*)&addrClient,&len);
		if(SOCKET_ERROR == iRet){ 
			printf("recvfrom failed !\n");
			closesocket(socketSrv);
			WSACleanup();
			return -1;
		}

		printf("Recv From Client:%s\n", strRecv);

		// 向客户端发送数据
		sendto(socketSrv, strSend, sizeof(strSend), 0, (SOCKADDR*)&addrClient, len);
	}
	
	closesocket(socketSrv);
	WSACleanup();

	return 0;
}

 

你可能感兴趣的:(C++)