gpt4 book ai didi

c - 通过c中的套接字发送结构

转载 作者:行者123 更新时间:2023-11-30 18:35:10 32 4
gpt4 key购买 nike

我想通过用 C 编写的 tcp 服务器/客户端程序中的套接字发送数据结构。但是,当我尝试打印发送的数据时,它不会打印任何内容。我现在已经意识到以这种方式发送结构是一个坏主意,我所看到的帖子对于找到实际实现这项工作的方法并没有多大帮助。这是有问题的数据结构:

#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

struct message{
char option[OPTLEN];
char user[USERLEN];
char buff[BUFFSIZE];
char target[USERLEN];
int sockid;
};

提前致谢。

最佳答案

对于相同的机器和编译器,您可以执行以下操作:

// define your structure:
#define BUFFSIZE 1024
#define USERLEN 32
#define OPTLEN 16

typedef struct message{
char option[OPTLEN];
char user[USERLEN];
char buff[BUFFSIZE];
char target[USERLEN];
int sockid;
}my_message;


// now you can use it in your program

my_message m;

// initialize m
...
strcpy(m.user,"1234");
...
m.sockid = sockfd;

// send it over

if ((nbytes = write(sockfd, &m, sizeof(my_message)) != sizeof(my_message))
{
printf("error writing my message");
}



// read the message on the other side:
...
my_message received_message;
int size;

if( (size = recv ( sockfd, (void*)&received_message, sizeof(my_message), 0)) >= 0)
{
// check the size
}

// It would work for same machines 32/64 bits and same compilers.

如果您需要更好的便携性,请尝试 protobuf-c , nanopb ,二进制序列化binntpl .

关于c - 通过c中的套接字发送结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47664715/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com