Python 3套接字传输端点已经连接问题

时间:2018-02-12 20:08:38

标签: python python-3.x sockets

我已经在Python3中编写了简单的IRC机器人,但是在不可靠的互联网断开连接后我尝试将机器人重新连接到IRC网络。我检测何时从服务器断开连接然后尝试使用异常处理程序,但异常处理程序总是给出相同的错误。我关闭套接字然后关闭然后创建新套接字但仍然已经连接端点并给出错误。

...
while True:
        try:
            buffer = buffer + self.irc.recv(1024).decode("utf-8", "replace")
        except ConnectionResetError:
            giveup = 0
            while giveup < 10:
                try:
                    self.irc.connect((self.SERVER, self.PORT))
                except (OSError, socket.gaierror) as e:
                    giveup = giveup + 1
                    print("Connection error, retrying in 90 seconds, attempt %s...\n" % giveup)
                    print(e)
                    self.irc.shutdown(socket.SHUT_RDWR)
                    self.irc.close()
                    self.irc = socket.socket()
                    self.irc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

                    time.sleep(90)

            if giveup == 10:
                print("Cannot re-establish connection. Exiting.")
                exit()

尝试重新连接时,此代码给出以下内容:

 ...
 [Errno 127] Transport endpoint is already connected
 Connection error, retrying in 90 seconds, attempt 9...
 [Errno 127] Transport endpoint is already connected
 Connection error, retrying in 90 seconds, attempt 10...
 [Errno 127] Transport endpoint is already connected
 Cannot re-establish connection. Exiting.

我不明白为什么传输端点已经连接。套接字正在关闭,新的套接字创建。可能是因为Porthas新的并且不了解某些东西。请帮忙,谢谢。

0 个答案:

没有答案