在服务器关闭时自动重新连接客户端套接字?

时间:2017-04-19 15:26:08

标签: python sockets

所以,今天早上我遇到了一个问题,我找不到任何已发布的答案。基本上,我希望每次服务器关闭时都让我的Python客户端重新连接。

我以前的代码看起来像这样

 def fire(self):
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.s.settimeout(5)

     while (self.connected):
         # create the transmission_struct class

         msg = transmission_struct(self.stream, self.CHUNK, self.rate)

         # create the Filestream packet

         packet1 = msg.structure_msg_fls()

         # create the decision packet

         packet2 = msg.structure_msg_stm()

         # send, first the decision packet
         self.s.sendall(packet2)

         # send the whole packet one by one

         for i in range(len(packet1)):
             self.s.sendall(packet1[i])

         # timestamp for debugging purposes

         ts = time.time()
         timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
         print(timestamp + " size of data sent is " + str(len(packet1)) +
               " size of decision is " + str(len(packet2)))

1 个答案:

答案 0 :(得分:0)

我通过tryexception块实现了重新连接逻辑,并在尝试函数中实现了递归。

 def fire(self):
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.s.settimeout(5)
     self.attempt_connect()

     while (self.connected):
         # create the transmission_struct class

         msg = transmission_struct(self.stream, self.CHUNK, self.rate)

         # create the Filestream packet

         packet1 = msg.structure_msg_fls()

         # create the decision packet

         packet2 = msg.structure_msg_stm()

         try:
             # send, first the decision packet
             self.s.sendall(packet2)

             # send the whole packet one by one

             for i in range(len(packet1)):
                 self.s.sendall(packet1[i])

             # timestamp for debugging purposes

             ts = time.time()
             timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
             print(timestamp + " size of data sent is " + str(len(packet1)) + " size of decision is " + str(len(packet2)))

         except socket.error as e:
             print(e.errno)
             self.connected = False
             print("Attempting to connect...")
             self.close_open_new_socket()
             time.sleep(1)
             continue

         except IOError as e:
             print(e.errno)
             self.close_open_new_socket()
             continue

         except KeyboardInterrupt:
             self.s.close()

         finally:
             self.attempt_connect()

 def attempt_connect(self):
     while (self.connected is False):
         try:
             self.result = self.s.connect((self.host, self.port))
             if (self.result == None):
                 self.connected = True
             else:
                 self.connected = False
         except socket.error as e:
             errorcode = e[0]
             print(errorcode)
             if (errorcode == 56):
                 self.connected = True
                 time.sleep(1)
                 continue
             elif(errorcode == 22):
                 self.connected = False
                 print("attempting to reconnect...")
                 # adding recursive call to attempt connect
                 # after socket is broken
                 self.close_open_new_socket()
                 time.sleep(1)
                 continue
             elif (errorcode == 61):
                 self.connected = False
                 print("Server not up, waiting for server and reconnecting...")
                 time.sleep(1)
                 continue
             elif (errorcode == 32):
                 self.connected = False
                 print("Server down, attempting to reconnect...")
                 time.sleep(1)
                 continue
             else:
                 self.connected = False
                 time.sleep(1)
                 continue

 def close_open_new_socket(self):
     self.s.close()
     self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.s.settimeout(5)
     self.attempt_connect()