如何在C ++(Unix)中设置UDP套接字的超时?

时间:2014-09-21 22:35:28

标签: c++ sockets unix udp timeout

我正在尝试为UDP套接字设置超时。在服务器端,我通过在大约1/3的时间内隐藏响应结构来模拟连接失败。我的代码工作正常,没有数据丢失,但我无法弄清楚如何在服务器没有响应时恢复客户端。这是代码:

struct request
{
    char clientIP[16];  /* Holds client IP address in dotted decimal */
    char m[24];         /* Name of machine on which client is running */
    int c;              /* Client number */
    int r;              /* Request number of client */
    int i;              /* Incarnation number of client’s machine */
    char operation[80]; /* File operation client sends to server */
};

struct returnValue
{
    int code;
    int bytes;
    char data[80];
};

void sendRequest(request myRequest)
{
    /* Send each request struct to the server */
    if((sendto(sock, &myRequest, sizeof(struct request), 0, (struct sockaddr *)
               &servAddr, sizeof(servAddr)) != sizeof(struct request)))
    {
        DieWithError("sendto() sent a different number of bytes than expected.");
    }
}

returnValue responseQuery(returnValue myReturn) /* Recv a response from server*/
{
    fromSize = sizeof(fromAddr);
    if ((respReqLen = recvfrom(sock, &myReturn, sizeof(struct returnValue), 0, (struct sockaddr *) &fromAddr, &fromSize)) != sizeof(struct returnValue))
    {
        DieWithError("recvfrom() failed");
    }
    if (servAddr.sin_addr.s_addr != fromAddr.sin_addr.s_addr)
    {
        fprintf(stderr,"Error: received a packet from unknown source.\n");
        exit(1);
    }
    return myReturn;
}

0 个答案:

没有答案