recv() returns always 0

六月ゝ 毕业季﹏ 提交于 2019-12-14 02:14:16

问题


I've a problem with recv() function that I can't explain: it always returns 0. I've a client/server application in which the server simply has to receive a string from the client through the internet (different pc).
There are no connectivity problems, and I also tried to send a string from server to client: it worked. I search in the blog and what I found, recv() socket function returning data with length as 0, non-blocking recv returns 0 when disconnected, Recv returning zero incorrectly, didn't help me to understand.

Here I post the Network class: Network.h

    class Network
    {
        WSADATA wsaData;
        WORD wVersionRequested;
        int Port;
        unsigned int byteReceived, byteSent; 
        SOCKET listeningSocket, connectedSocket; 
        SOCKADDR_IN serverAddr, senderInfo, clientAddr;
        int caddrlen;

    char buff[DIM];
    string buffer;
    public:
        Network();
        ~Network();

    void Recv();
};


Network.c

void Network::Recv() {
    int n = recv(connectedSocket, buff, strlen(buff), 0);

    setByteReceived(n);
    buffer.assign(buff, n);
    cout << "Buffer is: " << buff << endl; 
    if (byteReceived == 0)
        cout << "\tConnection closed" << endl;
    else if (byteReceived > 0) {
        cout << "\tByte received: " << byteReceived << endl;
        cout << getBuffer() << endl;
    }
    else {
        myFormatMessage(WSAGetLastError());
    }
}


The behaviour in the end is the following: client and server are connected, the server returns 0 from recv(). I tried also to run both programs on the same machine. Thank you for your help.


回答1:


You have:

void Network::Recv() {
    int n = recv(connectedSocket, buff, strlen(buff), 0);
    ...

If strlen(buff) returns 0 (because buff contains a null byte at index 0), you will be asking recv() to read 0 bytes, so it will return 0 bytes. You should be using sizeof(buff) instead of strlen(buff).



来源:https://stackoverflow.com/questions/39516683/recv-returns-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!