简体   繁体   中英

Tcp Socket recv function doesn't work c++

I am dealing with problem that after sending data successfully i recv the first response from the client but the second one after he put his details and submit not. do you have any idea why this happend? Here is my code:

    sock->listenAndAccept();
    string url="HTTP/1.1 302 Found \r\nContent-Type: text/html; charset=utf8 \r\nContent-        Length:279\r\n\r\n<!DOCTYPE html><html><head><title>Creating an HTML Element</title></head><body><form name=\"input\" action=\"login.html\" method=\"get\">user name: <input type=\"text\" name=\"user\"><br>password: <input type=\"text\" name=\"password\"><input type=\"submit\" value=\"Submit\"></form></body></html>";
    sock->send(url.data(),url.length());
    char buffer[1000];
    sock->recv(buffer, 1000);
    cout<<buffer<<endl;
    sock->recv(buffer, 1000);
    cout<<buffer<<endl;

listen and accept function:

TCPSocket* TCPSocket::listenAndAccept(){
    int rc = listen(socket_fd, 1);
    if (rc<0){
        return NULL;
    }
    size_t len = sizeof(peerAddr);
    bzero((char *) &peerAddr, sizeof(peerAddr));

    int connect_sock = accept(socket_fd, (struct sockaddr *)&peerAddr,(unsigned int *)&len);
    return new TCPSocket(connect_sock,serverAddr,peerAddr);
}

recv function:

int TCPSocket::recv(char* buffer, int length){
    return read(socket_fd,buffer,length);
}

TCP is stream oriented protocol. It might be possible that you have read all the messages in first recv. Check the size of received data and see if it matches the expected output.

Always always always (I can't say that often enough) check the return value of recv . recv will read up to the amount you have requested. If you're certain the amount you've requested is on its way then you must go into a loop around recv buffering incoming data until you've received what you expect to receive.

This kind of bug tends to sit there lurking unseen while you test on your local machine using the very fast localhost interface and then surfaces as soon as you start running the client and server on different hosts.

When you move on from your test code to actual code then you must also deal with zero length responses (client closed the socket) and error codes (<0 response).

Finally, please post your client code. There may be bugs there as well.

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