简体   繁体   中英

node.js http couldn't receive request from C++ clients via socket

I am trying to send GET request to nodejs server from a C++ client.

nodejs server:

const server = http.createServer((request, response) => {
    console.log(request.url);
    response.end("received");
})

and here is my C++ clients:

while(getline(cin, random_input)) {
    int s_len;
    input = "GET / HTTP/1.1\r\n\r\n";
    s_len = send(sock, input.c_str(), input.size(), 0);

    if( s_len < 0)
    {
        perror("Send failed : ");
        return false;
    }
    cout<<socket_c.receive(1024);
}

string tcp_client::receive(int size=512)
{
    char buffer[size];
    string reply;
    int r_len; // received len

    //Receive a reply from the server
    r_len = recv(sock, buffer, sizeof(buffer), 0);
    if( r_len < 0)
    {
        puts("recv failed");
    }

    if(buffer[r_len-1] == '\n') {
        buffer[r_len-1] = '\0';
    } else {
        buffer[r_len] = '\0';
    }
    reply = buffer;
    return reply;
}

so the C++ client can send GET requests each time when it's typing something in the terminal.

It works pretty fine if I type something right after the connection has been established. However, if I wait for 15-30 seconds after establish the connection, then type something on the client program, although the number of byte s_len that has been sent is correct, the server could't received anything.

May I know what goes wrong?

A few errors I spotted:

  1. send return value is not checked correctly. Condition input.size() == s_len must be true.
  2. recv return value is not checked of EOF . It treats r_len of 0 as valid data instead of disconnect. This may be the reason you do not see server replies: it may have disconnected but you did not notice that.

将node.js服务器的keepAliveTimeout的值设置为0可以解决问题

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