我想通过用 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 ,二进制序列化binn或tpl .
关于c - 通过c中的套接字发送结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47664715/