简体   繁体   English

Tcp Socket Recv函数不起作用C ++

[英]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: recv功能:

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

TCP is stream oriented protocol. TCP是面向流的协议。 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的返回值。 recv will read up to the amount you have requested. recv会读给你所要求的金额。 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. 如果您确定所请求的数量即将到来,则必须围绕recv缓冲传入数据进行循环,直到收到您希望收到的内容为止。

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. 当您使用非常快速的localhost接口在本地计算机上进行测试时,这种错误往往会潜伏在那里,然后在您在不同主机上运行客户端和服务器时立即浮出水面。

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). 从测试代码转到实际代码时,还必须处理长度为零的响应(客户端关闭了套接字)和错误代码(响应为<0)。

Finally, please post your client code. 最后,请发布您的客户代码。 There may be bugs there as well. 那里也可能有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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