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

标签 c sockets data-structures tcp structure

我想通过用 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/

相关文章:

objective-c - 如何让 modf 或 modff 正常工作?

javascript - Socket.io - 通过 Cloudflare 的 SSL

java - 如何使用套接字ping IP并通过它发送数据?

java - 比较存储在数组中的大量值的最有效方法是什么?

java - 可增长的多维数据结构,支持范围查询

c - 解释 "About size_t and ptrdiff_t"中的这段话

c - 如何调用结构的根/父级

c - 具有不同结果的宏参数

angularjs - Socket.io 未断开连接,xhr-polling 400 错误请求

objective-c - 如何在 Objective-C 中创建和使用队列?