简体   繁体   English

通过C ++中的UDP套接字发送struct,float和int

[英]Send struct, float and int over UDP sockets in C++

I want to send/receive structs containing float and int variables in client/server socket programs written in C++. 我想在用C ++编写的客户端/服务器套接字程序中发送/接收包含float和int变量的结构。

Earlier, the code was written in C, so I was simply sending them as follows: 之前,代码是用C编写的,因此我只是按以下方式发送它们:

//structure definition
struct {
    float a;
    float b;
    float c;
    float d[2];

}myStruct_;

//code to send struct
int slen = sizeof(client_sock)

if(recvfrom(sockFD, &myStruct_, sizeof(myStruct_), 0 ,(struct sockaddr *)&client_sock, &slen)<0) {
            printf("Failure while receiving data %d" , WSAGetLastError());
            getchar();
            exit(1);
}

But now in C++, this is giving me this error message: 但是现在在C ++中,这给了我这个错误消息:

error: cannot convert '(anonymous struct)*' to 'char *' for argument '2' to 'int recvfrom(SOCKET, char*, int, int, sockaddr*, int*)' 错误:无法将参数“ 2”的“(匿名结构)*”转换为“ char *”,转换为“ int recvfrom(SOCKET,char *,int,int,sockaddr *,int *)”

I tried to look for this error, and found out that I have to serialize the struct before sending, and later deserialize the same to get the exact structure. 我尝试查找此错误,发现在发送之前必须先对结构进行序列化,然后再反序列化该结构以获得确切的结构。 Could you suggest/or provide an example how to serialize and de-serialize it? 您能否建议/或提供一个示例,说明如何对其进行序列化和反序列化?

The code you showed will work fine in C++ with a little tweaking. 稍加调整,您显示的代码即可在C ++中正常工作。

In some platforms (like Linux), recvfrom() is defined as expecting a void* pointer to the memory buffer that it will fill in. In other platforms (like Windows), recvfrom() expects a char* pointer instead. 在某些平台(例如Linux)中, recvfrom()被定义为期望指向将要填充的内存缓冲区的void*指针。在其他平台(例如Windows)中, recvfrom()期望使用char*指针。

To get rid of the error, simply type-cast the buffer pointer (just like you do with the 5th parameter, where you are passing a sockaddr_in* pointer where a sockaddr* pointer is expected): 要消除此错误,只需简单地键入缓冲区指针的类型(就像您对第5个参数所做的那样,即在其中传递sockaddr_in*指针的地方,其中应该使用sockaddr*指针):

recvfrom(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&client_sock, &slen);

Do the same thing when sending a struct: 发送结构时执行相同的操作:

sendto(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&server_sock, &slen);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM