简体   繁体   中英

Strange behavior of send in c++ socket connection

I'm experimenting with the tcp socket connection under c++. I would like to send the serialized (JSON) form of an std::map object over the network. I found out that after a certain amount of packets (this depends on the packet size) have been sent, sending is just not possible anymore. I have tried both the curl lib and the standard POSIX API for the socket connection:

  • send in POSIX API: it starts to block after ~100 packets have been sent
  • curl: curl_easy_send seems to be executed but the server does not receive a new packet

During the communication the same socket connection is used.I guess the whole thing is related to the buffer size, but (1) I have increased it and did not see any significant effect (2) I would expect that sending would be possible again after a given amount of time if the buffer is full currently. Maybe I'm missing something important but silly option or info in this situation. So my question is: is the configuration of the server wrong or do I not use the APIs in a correct way?

Receiver side:

ListenerThread::ListenerThread() {
    curl = curl_easy_init();

    if (curl != 0) {
        curl_easy_setopt(curl, CURLOPT_URL, "...");
        curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L);
        res = curl_easy_perform(curl);
        res = curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockfd);

        if (res != 0) {
            printf("Error: %s\n", curl_easy_strerror(res));
        }
    }
}
...
void ListenerThread::run() {
    while (true) {
        char buf[2048];

        wait_on_socket(sockfd, 1, 60000L);
        res = curl_easy_recv(curl, buf, 2048, &iolen);

        if (CURLE_OK != res) {
            break;
        }

        nread = (curl_off_t) iolen;

        printf("Received %" CURL_FORMAT_CURL_OFF_T " bytes.\n", nread);
        printf("Buffer: %s\n", buf);
    }
}

It could happen if the peer is not reading the data your are sending.

The packets get into the receive buffer of the socket on the other end and the ACKs are sent back to you, so some amount of data gets confirmed and is discarded from your socket send buffer. However, if the peer is not extracting the data from its receive buffer, it eventually gets full and you cannot send any data until some place is freed there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM