多TCP连接已断开,并且在python中不再连接

时间:2019-05-08 07:33:41

标签: python-3.x python-2.7 tcp

我正在编写一个用于跟踪设备的python程序。该程序组织数据并将其保存到数据库。但是我有一个问题。当跟踪设备的Internet断开连接,然后再次连接到Internet时,程序将停止从该设备接收数据。我必须再次启动程序。如何使其重新连接?

我也尝试了Python2.x和3.x tcp编程,但是当设备断开连接并返回服务器时,它也不会发送数据。

我将传入的数据保存在一个文本文件中。然后,我将传入的数据保存在数据库中。我这样做是为了防止数据丢失。

    import socket  
    import sys
    import thread
    import os
    import MySQLdb
    from datetime import datetime, timedelta


    class DB:
      conn = None

      def connect(self):
        self.conn = MySQLdb.connect(dbhost, dbuser, dbpass, dbname)

      def query(self, sql):
        try:
          cursor = self.conn.cursor()
          cursor.execute(sql)
        except (AttributeError, MySQLdb.OperationalError):
          self.connect()
          cursor = self.conn.cursor()
          cursor.execute(sql)
          self.conn.commit()
          self.conn.autocommit(True)
        return cursor

    def db_insert(mesaj):
      try: 

        parcala = mesaj.split("#")
        i=0
        j=len(parcala)


        cur = db.query('INSERT INTO ...')


        while i < (j-1):
                #db insert
        #print addr, ' >> ', mesaj
      except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        i = i + 1
      finally:
        cur = db.query('INSERT INTO log ...')

    def on_new_client(clientsocket,addr):
      while True:
        try:
          dosya_ismi = "/etc/logs/"+str(addr[0])+".txt"
          dosya_ismi = dosya_ismi.replace(',','')
          dosya_ismi = dosya_ismi.replace(' ','')
          msg = clientsocket.recv(1024)
          dosya = open('/etc/tcplog.txt','a')
          dosya.write('\n')
          dosya.write(msg)
          dosya.flush()
          dosya.close() 
          if len(msg) < 2:
            cur = db.query('INSERT INTO log')
            break
          try:
            dosya = open(str(dosya_ismi),'a')
            msg = msg.replace('\n','')
            msg = msg.replace(' ','')
            dosya.write(msg)
            dosya.flush()
            dosya.close() 
          except IOError:
            print "Dosya yazma hatasi"
            cur = db.query('INSERT INTO log')
          try:
            #with open('gash.txt', 'r') as var:
             # for line in var:
              #  line = line.rstrip()
            #dosya.close()
            dosya=open(str(dosya_ismi),"r+")
            veri=dosya.read()  
            veri.replace('\n','')
            veri.replace(' ','')
            son = veri.rfind("#")
            son = son + 1
            veri_kaydet = veri[:son]
            cur = db.query('INSERT INTO log')
            db_insert(veri_kaydet)
            dosya.close()
            os.remove(str(dosya_ismi))
            dosya = open(str(dosya_ismi),'w')
            veri = veri.replace('\n','')
            veri = veri.replace(' ','')
            dosya.write(veri[son:])
            dosya.flush()
            dosya.close()

          except IOError:
            print "Dosya okuma hatasi"
            dosya = open(str(dosya_ismi),'w')
            veri = veri.replace('\n','')
            veri = veri.replace(' ','')
            dosya.write(veri[son:])
            dosya.flush()
            dosya.close()
            cur = db.query('INSERT INTO log')
        finally:
          print addr, ' >> ', msg


    s = socket.socket()         # Create a socket object
    host = 'serveripaddr'    # Get local machine name
    port = serverport                 # Reserve a port for your service.
    s.bind((host, port))        # Bind to the port
    s.listen(50)                 # Now wait for client connection.

    #con = MySQLdb.connect(dbhost, dbuser, dbpass, dbname);
    db = DB()

    while True:
       c, addr = s.accept()     # Establish connection with client
       #c.setblocking(0)
       thread.start_new_thread(on_new_client,(c,addr))
       #Note it's (addr,) not (addr) because second parameter is a tuple
       #Edit: (c,addr)

来自端口的数据有时可能大于1024个字符。数据库可能会给出错误并退出程序,或者设备已重新连接到服务器,因此它可以退出程序。

在出现任何数据库错误时,如何再次将其返回数据库,或者在设备与服务器断开连接后重新连接该线程?

0 个答案:

没有答案