1. 程式人生 > >vc++ union 體中多個struct ,udp資料傳輸服務端客戶端收發資訊不一致問題 求解 。。。。。。

vc++ union 體中多個struct ,udp資料傳輸服務端客戶端收發資訊不一致問題 求解 。。。。。。

最近接觸了一下 vc++ socket udp 傳送union 結構體資料收發端資料不一致問題 ,目的是用C#向vc++ udp服務端傳送結構體資料,但是試了C#中的結構體對齊方式,但始終資料不一致,所以直接用vc++寫了個 vc++的demo客戶端 和服務端,發現的問題跟C# 對接vc++一樣,求解。。。。。。

下面直接上模擬vc++客戶端,服務端執行程式碼及執行截圖:

#傳輸資料結構體
	struct S_Data
	{
		char flag[4]; 
		int ab;
		int num;
		union
		{
			struct
			{
				long				p2;	
				long				p3;			// 買三價
			};
			struct
			{
				long				p4;
			};
		};
	};



#Udp 服務端:
	#include "pch.h"
	#include <iostream>
	#include <stdio.h>
	#include <winsock2.h>
	#include <atltime.h>
	#pragma comment(lib,"ws2_32.lib")
	#define SERVERPORT 6001
	int main(void)
	{
		WORD wVersionRequested;
		WSADATA wsaData;
		int err;
		wVersionRequested = MAKEWORD(2, 2);
		err = WSAStartup(wVersionRequested, &wsaData);
		if (err != 0) {
			return -1;
		}
		if (LOBYTE(wsaData.wVersion) != 2 ||
			HIBYTE(wsaData.wVersion) != 2) {
			WSACleanup();
			return -1;
		}
		
		SOCKET sockServer = socket(AF_INET, SOCK_DGRAM, 0);
		if (INVALID_SOCKET == sockServer)
		{
			printf("called failed! The error code is: %d\n", WSAGetLastError());
			return -1;
		}
		else
		{
			printf("socket() called succesful!\n");
		}

		//伺服器端
		SOCKADDR_IN addrServer;
		addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
		addrServer.sin_family = AF_INET;
		addrServer.sin_port = htons(SERVERPORT);

		//繫結套接字
		err = bind(sockServer, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));
		if (SOCKET_ERROR == err)
		{
			printf("bind() called failed! The error code is: %d\n", WSAGetLastError());
			return -1;
		}
		else
		{
			printf("bind called successful!\n");
		}
		while (TRUE)
		{
			SOCKADDR_IN addrClient;
			int len = sizeof(SOCKADDR);
			char recvBuf[1024] = "\0";
			recvfrom(sockServer, recvBuf, 1024, 0, (SOCKADDR*)&addrClient, &len);
			S_Data *data = (TUDPDATAs *)malloc(sizeof(S_Data));
			memcpy(data, recvBuf, sizeof(S_Data));

			int temp = 0;
		}
		closesocket(sockServer);
		WSACleanup();
		return 0;
	}


#Udp 客戶端:

	SOCKET m_socket;
	SOCKADDR_IN serverAddr;
	int m_nLen;
	
	USES_CONVERSION;
	char * ip = W2A(L"127.0.0.1"); 
	u_short port = atoi(W2A(L"6001"));
	m_socket = socket(AF_INET, SOCK_DGRAM, 0);
	serverAddr.sin_addr.S_un.S_addr = inet_addr(ip);
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(port);
	m_nLen = sizeof(SOCKADDR);

	S_Data data;
	memcpy_s(data.flag, 4, "HSHS", 4);
	data.ab = 1024;
	data.num = 100;
	data.p2 = 2 * 10000;
	data.p3 = 3 * 10000;
	data.p4 = 4 * 10000;

	int t = sizeof(data);
	int ret = sendto(m_socket, (char *)&data, sizeof(data), 0, (SOCKADDR*)&serverAddr, m_nLen);

執行結果如圖:

udp客戶端傳送結構資料如圖:

客戶端結構體資料
標題

udp服務端接收結構資料如圖:

服務端結構體資料
標題