recv来自服务器的传入流量

时间:2010-11-22 11:55:06

标签: c++ windows tcp

我有以下功能设置,每2分钟从服务器接收一次数据。我第一次调用该函数它似乎工作,但它在recv调用时冻结,它永远不会返回。我是否需要在每次调用时分配缓冲区,即使服务器没有任何内容可以发送?

#define RCVBUFSIZE 32

void Receive()
{   
    UINT totalBytesRcvd = 0, bytesRcvd = 0;
    char buffer[RCVBUFSIZE];     /* Buffer for string */

    /* Receive up to the buffer size (minus 1 to leave space for 
    a null terminator) bytes from the sender */

    bytesRcvd = recv(sockClient, buffer, RCVBUFSIZE - 1, 0);

    if (bytesRcvd)
    {
        buffer[bytesRcvd] = '\0';
        MessageBox(0, buffer, 0, 0); //some way to display the received buffer
    }
    else if (bytesRcvd == SOCKET_ERROR)
    {
        return;
    }
}

1 个答案:

答案 0 :(得分:5)

(1)您的缓冲区未真正分配,它位于堆栈中。您通常不必担心在堆栈上使用32个字节。

(2)recv应该阻止,直到它有东西要接收。您可以使用非阻塞套接字或使用select来解决这个问题。请参阅here以供参考。

特别是,你可以

(2a)使用ioctlsocket将套接字设置为非阻塞模式。然后,当您致电read并且无法阅读时,您会收到错误EWOULDBLOCK

unsigned long non_blocking = 1;
ioctlsocket (sockClient, FIONBIO, &non_blocking);

然后阅读成为

bytesRcvd = recv(sockClient, buffer, RCVBUFSIZE - 1, 0);
if (bytesRcvd == -1) {
    if (WSAGetLastError() == EWOULDBLOCK) {
        // nothing to read now
    } else {
        // an actual error occurred
    }
} else {
    // reading was successful. Call to MsgBox here
}

(2b)或者,在实际调用read之前,您可以致电select以确定是否有要阅读的数据。

struct timeval timeout;
timeout.tv_usec = 0;
timeout.tv_sec = 0;

fd_set r;
FD_ZERO (&r);
FD_SET (sockClient, &r);
switch (select (sockClient + 1, &r, NULL, NULL, &timeout)) {
    case -1:
        // error
        break;
    case 0:
        // nothing to read
        break;
    case 1:
        // you may call read ()
        break;
}
相关问题