一个最简单的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;  
}


你可能感兴趣的:(网络编程深入研究,网络编程)