如何捕捉"通过对等体QUOT连接复位;错误交流电插座? [英] How to catch a "connection reset by peer" error in C socket?

查看:189
本文介绍了如何捕捉"通过对等体QUOT连接复位;错误交流电插座?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++和Qt的应用程序,它的一部分实现了交流电插座客户端。通过应用前段时间由于坠毁事情发生在服务器;我从碰撞获得了唯一的事情就是Qt Creator中的应用程序输出说明消息

I have a C++ and Qt application which part of it implements a C socket client. Some time ago by app crashed because something happened with the server; the only thing I got from that crash was a message in Qt Creator's Application Output stating

recv_from_client:连接被对方​​重置

recv_from_client: Connection reset by peer

我做了这个错误的对等连接复位在网络上的一些研究,而在这里的某些线程SO等地也设法解释是怎么回事,他们没有说明如何处理它 - 也就是说,我怎么能捕获的错误并继续我的应用程序,而不崩溃(特别是当我从服务器读取是一个while循环内的方法,所以I'ld要停止while循环,并在我的$ C的另一处进入$ C,将尝试重新建立连接)。

I did some research on the web about this "connection reset by peer" error and while some threads here in SO and other places did managed to explain what is going on, none of them tells how to handle it - that is, how can I "catch" the error and continue my application without a crash (particularly the method where I read from the server is inside a while loop, so I'ld like to stop the while loop and enter in another place of my code that will try to re-establish the connection).

因此​​,如何能赶上我这个错误妥善处理呢?不要忘了,我的code实际上是C ++使用Qt - 对C部分,是调用socket方法,库

So how can I catch this error to handle it appropriately? Don't forget that my code is actually C++ with Qt - the C part is a library which calls the socket methods.

修改

顺便说一下,从该碰撞起源的可能方法(给予上述错误信息的recv_from_client部分)为:

Btw, the probable method from which the crash originated (given the "recv_from_client" part of the error message above) was:

int hal_socket_read_from_client(socket_t *obj, u_int8_t *buffer, int size)
{
    struct s_socket_private * const socket_obj = (struct s_socket_private *)obj;
    int retval = recv(socket_obj->client_fd, buffer, size, MSG_DONTWAIT); //last = 0

    if (retval < 0)
        perror("recv_from_client");

    return retval;
}

请注意:我不知道如果这个错误发生时,的recv 配置与的 MSG_DONTWAIT 的或的 0

Note: I'm not sure if by the time this error occurred, the recv configuration was with MSG_DONTWAIT or with 0.

推荐答案

只是检查错误号阅读()返回结果为负。

Just examine errno when read() returns a negative result.

有通常不涉及崩溃。

while (...) {
    ssize_t amt = read(sock, buf, size);
    if (amt > 0) {
        // success
    } else if (amt == 0) {
        // remote shutdown (EOF)
    } else {
        // error

        // Interrupted by signal, try again
        if (errno == EINTR)
            continue;

        // This is fatal... you have to close the socket and reconnect
        // handle errno == ECONNRESET here

        // If you use non-blocking sockets, you also have to handle
        // EWOULDBLOCK / EAGAIN here

        return;
    }
}

这篇关于如何捕捉&QUOT;通过对等体QUOT连接复位;错误交流电插座?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆