我的头文件structure.h中具有以下结构。现在,我需要在main.c文件中使用此结构。

我需要用一些值填充此结构,并且需要将其从TCP/IP客户端发送到同一系统上的TCP/IP服务器。

#ifndef STRUCTURE_H
#define STRUCTURE_H

typedef struct
{
    unsigned int variable3;
    char variable4[8];
}NUMBER_ONE,*PNUMBER_ONE;


typedef struct
{
    unsigned int variable5;
    char variable6[8];
}NUMBER_TWO,*PNUMBER_TWO;

typedef struct
{
    char name[32];
    unsigned int a;
    unsigned int b;
    NUMBER_ONE variable1;
    NUMBER_TWO variable2;
}NUMBER_THREE,*PNUMBER_THREE;

#endif

我已经尝试过了,但是我在C语言方面并不擅长,因此请以上述结构为例,谁能告诉我该怎么做?直到套接字连接建立对我来说还可以,
但是建立连接后,如何将这种结构从客户端发送到服务器?

我正在我的Linux Ubuntu 12.04系统中执行此操作。

最佳答案

使用套接字发送信息时,可以使用以下三种方式:

1)固定大小的消息(我们将使用它,并假设我们在同一台机器上按字节顺序进行写入)简单来说,就像我们将发送100字节并在接收时将读取100字节

2)message.len + message。(首先我们发送消息len,然后发送消息本身。主要用于二进制发送接收)

3)标记方法(通常用于发送文本消息或命令。例如,使用\n换行符进行标记)

接下来是代表我们的数据(序列化)。使用c原因很容易,因为我们可以直接编写对象并检索它而无需额外的努力。对象将与内存中的对象相同。

// PNUMBER_THREE structAddr;
    send(socket_id, structAddr, sizeof(NUMBER_THREE), 0);

或者
 write(socket_id, structAddr, sizeof(NUMBER_THREE));

或更安全
write_socket(socket_id, structAddr, sizeof(NUMBER_THREE));
//It is safer to do so though we are using blocking mode
int write_socket(int fd,const char *buf,int len){
    int currentsize=0;
    while(currentsize<len){
        int count=write(fd,buf+currentsize,len-currentsize);
        if(count<0) return -1;
        currentsize+=count;
    }
    return currentsize;
}

阅读时,我们将使用相同的结构,并且必须满足条件sizeof(NUMBER_THREE)==SizeInsideClient //SizeInsideClient is sizeof on client SizeInsideClient=sizeof(NUMBER_THREE)
   //SizeInsideClient structure size on client program
    assert(sizeof(NUMBER_THREE)==SizeInsideClient);
    readblock(socket_id,structAddr,sizeof(NUMBER_THREE));

    int readblock(int fd, char* buffer, int len) {
        int ret  = 0;
        int count = 0;
        while (count < len) {
            ret = read(fd, buffer + count, len - count);
            if (ret <= 0) {
                return (-1);
            }
            count += ret;
        }
        return count;

    }

09-10 11:04
查看更多