socket c客户端没有收到字符串

时间:2012-06-17 15:06:09

标签: c sockets

这是客户端代码的片段:

connect(DescrittoreClient, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

strcpy(Buffer, filename);

send(DescrittoreClient, Buffer, strlen(Buffer), 0);
fd = open(filename, O_CREAT | O_WRONLY,0644);

while ((nread = read(DescrittoreClient, Buffer, sizeof(Buffer))) != 0) {
    write(fd, Buffer, nread);
    memset(Buffer,0,sizeof(Buffer));
}
int gg;
while( (gg = recv(DescrittoreClient, Buffer, sizeof(Buffer), 0)) == -1) continue;
printf("%d\n", gg);
printf("Risposta del server: %s\n", Buffer);

close(DescrittoreClient);
return EXIT_SUCCESS;

这是服务器代码的片段:

while(1){

    rc = recv(DescrittoreClient, filename, sizeof(filename), 0);

    fd = open(filename, O_RDONLY);

    fstat(fd, &stat_buf);

    offset = 0;
    rc = sendfile(DescrittoreClient, fd, &offset, stat_buf.st_size);
    if (rc != stat_buf.st_size) {
        fprintf(stderr, "incomplete transfer from sendfile: %d of %d bytes\n", rc, (int)stat_buf.st_size);
        exit(1);
    }
    strcpy(Buffer, "Dati inviati correttamente");
    if( (send(DescrittoreClient, Buffer, strlen(Buffer), 0)) == -1){
        printf("Errore nell'invio della stringa\n");
        close(DescrittoreClient);
        close(fd);
        exit(1);
    }

}
close(DescrittoreServer);
return EXIT_SUCCESS;

这是预期的行为:

Client --Give me file X--> Server
Server --send the file X--> Client
Server -->send string "File has been sent"--> Client

但这是真实行为:

Client --Give me file X--> Server
Server --send the file X--> Client
Server -->_NOTHING_--> Client

所以问题是客户端没有收到“文件已发送”。我已经检查过问题是服务器端但是不是(事实上服务器发送字符串)

1 个答案:

答案 0 :(得分:2)

(基于上面的评论) - 要实现的是TCP通信是100%基于流的,没有内置的框架。这意味着所有TCP层都确保接收方以发送方发送的相同顺序接收字节 - 但保证将以相同的间隔接收字节因为他们被送了。 (例如,如果发送()10个字节,然后20个字节,然后50个字节,接收器可能一次接收所有80个字节,或者63个字节接着17个字节,或者汇总到的任何其他recv()的组合总共80个字节。

因此,为了以接收者可以正确解释它们的方式发送多个单独的项目,您需要定义自己的规则来构建数据。在您的情况下,您需要发送 n 字节的文件数据,后跟一个字符串,接收程序需要知道的是文件数据的字节数。这样,一旦收到(那么多)字节,它就知道剩余的字节是字符串数据,而不只是将它们写入文件。

我的建议是首先发送文件的大小(如果需要支持大于4千兆字节的文件大小,则为4字节整数或8字节长)。然后接收代码将是这样的:

  1. 接收4个字节
  2. 将这四个字节解释为整数(您可能希望通过发送方的htonl()和接收方的ntohl()传递此值,以避免此处可能存在的字符串问题)
  3. 接收N个字节并将其写入文件
  4. 将任何剩余字节作为字符串接收。