我尝试将结构从客户端发送到服务器。我在互联网上读到我必须将结构类型转换为 char 数组,但是当我尝试这个时,char 没有内容。
这是我的结构:
struct packet
{
int pa_ID;
char message[MESSAGESIZE];
};
在这里我尝试发送结构:
int sendFile(FILE *file, SOCKET sock)
{
int amountToSend, amountSent;
int i = 0;
char buffer[BUFFERSIZE], serializedPacket[BUFFERSIZE];
while (!feof(file)) {
struct packet p;
fgets(p.message, MESSAGESIZE, file);
p.pa_ID = i;
if (p.message[strlen(p.message) - 1] == '\n')
p.message[strlen(p.message) - 1] = '\0';
amountToSend = sprintf_s(serializedPacket, sizeof(buffer), (char*)&p);
amountSent = send(sock, serializedPacket, amountToSend, 0);
if (amountSent == SOCKET_ERROR) {
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
getchar();
WSACleanup();
return -1;
}
printf("Send %d bytes (out of %d bytes) of data: [%.*s]\n", amountSent, amountToSend, amountToSend, serializedPacket);
memset(buffer, 0, sizeof(buffer));
memset(p.message, 0, sizeof(p.message));
memset(&p, 0, sizeof(p));
i++;
}
fclose(file);
return 0;
}
从文件中读取功能没有错误,但是 serializedPack 只是空的,我真的不明白为什么。希望有人可以提供帮助。