0

At server.cpp I have two int fields to send to client.cpp. I am sending in this way:

 if ((bytecount = send(*csock, portstring1, strlen(portstring1), 0)) == -1) {
    fprintf(stderr, "Error sending data %d\n", errno);
    goto FINISH;
    }

        sprintf(portstring2, "%d", ncount);
 if ((bytecount = send(*csock, portstring2, strlen(portstring2), 0)) == -1) {
    fprintf(stderr, "Error sending data %d\n", errno);
    goto FINISH;
    }

and at receiver side I use:

if((bytecount = recv(hsock, buffer, buffer_len, 0))== -1){
        fprintf(stderr, "Error receiving data %d\n", errno);
        goto FINISH;
    }
    printf("Positive counts are :");
    printf(" %s \n",buffer);

if((bytecount = recv(hsock, buffer2, buffer_len, 0))== -1){
        fprintf(stderr, "Error receiving data %d\n", errno);
        goto FINISH;
    }
    printf("Negative count is :");
    printf(" %s \n",buffer2);

But problem is that first rec() function catch both values sent from server and does not reach to second receive function. When I print data received from first rec function it show both values sent from server.

I tried using array to send both values togather but then converting int array to chat * became headache for me. Because send and rec function deal with char * values only. Not even string.

Any idea, how can I get both values at seperate level at client side?

4

1 回答 1

0

接收方无法知道您发送的是 2 个项目还是单个大项目。您可能需要在此处实现自己的协议。

如果您知道每个项目的大小,则可以尝试从 recv 缓冲区中仅读取那么多。如果项目大小不同,您可以简单地先发送大小,然后再发送项目,以便在接收端您可以先读取整数,然后将缓冲区设置为该大小并读取剩余部分。

在您的情况下,每个发送的前缀都带有接收端的字符串长度(4 个字节),读取 4 个字节并将其转换为 int32,您将获得要读取的消息的长度。现在您可以将缓冲区大小设置为所需大小并读取。

正如 Damien_The_Unbeliever 所提到的,您无法确保一口气收到完整的消息,您可能需要循环阅读。

于 2013-06-26T06:54:30.170 回答