c++实现组播和广播的发送和接收端

  1. 广播
    • 接收端
    #include 
    #include 
    #include 
    #include 
    #include "MsgDefForDataServer23Tai.h"
    #include "LocatorData.h"
    
    #pragma comment(lib, "ws2_32.lib")
    using namespace PT_TAI;
    
    int main()
    {
    	WSADATA wsaData;
    	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    	if (iResult != 0) {
    		std::cout << "WSAStartup failed: " << iResult << std::endl;
    		return 1;
    	}
    
    	SOCKET recvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    	if (recvSocket == INVALID_SOCKET) {
    		std::cout << "socket failed with error: " << WSAGetLastError() << std::endl;
    		WSACleanup();
    		return 1;
    	}
    
    	sockaddr_in recvAddr;
    	recvAddr.sin_family = AF_INET;
    	recvAddr.sin_port = htons(9632);
    	recvAddr.sin_addr.s_addr = INADDR_ANY;
    
    	iResult = bind(recvSocket, (sockaddr*)&recvAddr, sizeof(recvAddr));
    	if (iResult == SOCKET_ERROR) {
    		std::cout << "bind failed with error: " << WSAGetLastError() << std::endl;
    		closesocket(recvSocket);
    		WSACleanup();
    		return 1;
    	}
    
    	// char recvBuf[1024] = { 0 };
    	// char recvBuf[11 * 1024] = { 0 };
    	char recvBuf[11 * 1603] = { 0 };
    	int recvBufLen = sizeof(recvBuf);
    	struct sockaddr_in senderAddr;
    	int senderAddrLen = sizeof(senderAddr);
    
    	while (true) {
    		iResult = recvfrom(recvSocket, recvBuf, recvBufLen, 0, (struct sockaddr*)&senderAddr, &senderAddrLen);
    		if (iResult == SOCKET_ERROR) {
    			std::cout << "recvfrom failed with error: " << WSAGetLastError() << std::endl;
    			closesocket(recvSocket);
    			WSACleanup();
    			continue;
    			// return 1;
    		}
    
    		std::vector<ST_DATA_SEND> vecValue;
    		std::string strReceiveData;
    		strReceiveData.resize(iResult);
    		std::memcpy((void*)strReceiveData.data(), recvBuf, iResult);
    		int nSize = CCLocatorData->DeserializeResult(strReceiveData, vecValue);
    		std::cout << "--------------------------------------------------------" << std::endl;
    		for (auto Item : vecValue)
    		{
    			std::cout << static_cast<int>(Item.iVersion) << "\t" << Item.szDeviceID << std::endl;
    		}
    
    		std::cout << "Received " << iResult << " bytes: " << recvBuf << " from " << inet_ntoa(senderAddr.sin_addr) << std::endl;
    	}
    
    	closesocket(recvSocket);
    	WSACleanup();
    
    	return 0;
    }
    
    
  • 发送端
   #include 
   #include 
   #include 
   
   #pragma comment(lib, "ws2_32.lib")
   
   int main()
   {
   	WSADATA wsaData;
   	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
   	if (iResult != 0) {
   		std::cout << "WSAStartup failed: " << iResult << std::endl;
   		return 1;
   	}
   
   	SOCKET sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
   	if (sendSocket == INVALID_SOCKET) {
   		std::cout << "socket failed with error: " << WSAGetLastError() << std::endl;
   		WSACleanup();
   		return 1;
   	}
   
   	BOOL broadcast = TRUE;
   	iResult = setsockopt(sendSocket, SOL_SOCKET, SO_BROADCAST, (char*)&broadcast, sizeof(broadcast));
   	if (iResult == SOCKET_ERROR) {
   		std::cout << "setsockopt failed with error: " << WSAGetLastError() << std::endl;
   		closesocket(sendSocket);
   		WSACleanup();
   		return 1;
   	}
   
   	sockaddr_in sendAddr;
   	sendAddr.sin_family = AF_INET;
   	sendAddr.sin_port = htons(9632);
   	inet_pton(AF_INET, "255.255.255.255", &(sendAddr.sin_addr));
   
   	const char* sendData = "Hello, broadcast!";
   	int sendDataLen = strlen(sendData);
   
   	while (true) {
   		iResult = sendto(sendSocket, sendData, sendDataLen, 0, (sockaddr*)&sendAddr, sizeof(sendAddr));
   		if (iResult == SOCKET_ERROR) {
   			std::cout << "sendto failed with error: " << WSAGetLastError() << std::endl;
   			closesocket(sendSocket);
   			WSACleanup();
   			return 1;
   		}
   
   		std::cout << "Sent " << iResult << " bytes: " << sendData << std::endl;
   		Sleep(1000); // 每隔1秒发送一次数据
   	}
   
   	closesocket(sendSocket);
   	WSACleanup();
   
   	return 0;
   }
  1. 组播
  • 发送端
	#include 
	#include 
	#include 
	#include 
	
	#pragma comment(lib, "ws2_32.lib")
	
	int main() {
		WSADATA wsaData;
		if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
			std::cerr << "Failed to initialize winsock" << std::endl;
			return 1;
		}
	
		SOCKET sockfd;
		struct sockaddr_in addr;
		const char* group = "239.0.0.1";
		const int port = 8888;
	
		// 创建UDP套接字
		sockfd = socket(AF_INET, SOCK_DGRAM, 0);
		if (sockfd == INVALID_SOCKET) {
			std::cerr << "Failed to create socket" << std::endl;
			WSACleanup();
			return 1;
		}
	
		// 设置组播地址和端口
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = inet_addr(group);
		addr.sin_port = htons(port);
	
		std::string message = "Hello, multicast!";
	
		while (true) {
			// 发送消息
			if (sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
				std::cerr << "Failed to send message" << std::endl;
				closesocket(sockfd);
				WSACleanup();
				return 1;
			}
	
			std::cout << "Message sent" << std::endl;
	
			Sleep(1000); // 暂停1秒钟
		}
	
		// 关闭套接字
		closesocket(sockfd);
		WSACleanup();
	
		return 0;
	}
  • 接收端
	#include 
	#include 
	#include 
	#include 
	
	#pragma comment(lib, "ws2_32.lib")
	
	int main() {
		WSADATA wsaData;
		if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
			std::cerr << "Failed to initialize winsock" << std::endl;
			return 1;
		}
	
		SOCKET sockfd;
		struct sockaddr_in addr;
		const char* group = "239.0.0.1";
		const int port = 8888;
	
		// 创建UDP套接字
		sockfd = socket(AF_INET, SOCK_DGRAM, 0);
		if (sockfd == INVALID_SOCKET) {
			std::cerr << "Failed to create socket" << std::endl;
			WSACleanup();
			return 1;
		}
	
		// 设置组播地址和端口
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(port);
	
		// 绑定套接字到本地地址和端口
		if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
			std::cerr << "Failed to bind socket" << std::endl;
			closesocket(sockfd);
			WSACleanup();
			return 1;
		}
	
		// 加入组播组
		struct ip_mreq mreq;
		mreq.imr_multiaddr.s_addr = inet_addr(group);
		mreq.imr_interface.s_addr = htonl(INADDR_ANY);
		if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) == SOCKET_ERROR) {
			std::cerr << "Failed to join multicast group" << std::endl;
			closesocket(sockfd);
			WSACleanup();
			return 1;
		}
	
		char buffer[1024];
		struct sockaddr_in senderAddr;
		int senderAddrLen = sizeof(senderAddr);
	
		while (true) {
			// 接收消息
			int numBytes = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&senderAddr, &senderAddrLen);
			if (numBytes == SOCKET_ERROR) {
				std::cerr << "Failed to receive message" << std::endl;
				closesocket(sockfd);
				WSACleanup();
				return 1;
			}
	
			buffer[numBytes] = '\0';
			std::cout << "Received message from " << inet_ntoa(senderAddr.sin_addr) << ": " << buffer << std::endl;
		}
	
		// 关闭套接字
		closesocket(sockfd);
		WSACleanup();
	
		return 0;
	}

你可能感兴趣的:(c++,开发语言)