Errno 61 Connection refused & Errno 54 Connection reset by peer on Echo Server
<p>I'm looking for some help!!!!! I'm some what new to Python so please beare with me. I'm trying to create an Echo Server with to Clients in Side it. One checking a MySQL and the other checking a port on the server. The Clients are sending the data to the Echo Server and the server send the data back out to all connected Clients.</p>

<p>It runs for about 2 hours then I get errors like:</p>

<pre><code>[Errno 54] Connection reset by peer
[Errno 61] Connection refused
</code></pre>

<p>System:
MAC OS X Lion 10.7.3
Memory: 5GB
Processor: 2.2 GHz Intel Core 2 Duo</p>

<p>Is this the best way to do this?
What is the best way? Please Help.</p>

<p>Here is my code:</p>

<pre><code>class Database(Process):
    def __init__(self):
        super(Database, self).__init__()
        self.is_stop = Event()
        self.is_stop.clear()
        _cfg          = cfg.Config().DataBase()
        self.dbHost   = _cfg.dbHost
        self.dbUser   = _cfg.dbUser
        self.dbPass   = _cfg.dbPass
        self.dbName   = _cfg.dbName
        self.dbPort   = _cfg.dbPort

    def run(self):
        print "Database pid %s" % self.pid

        while not self.is_stop.is_set():
            rows = self.getData()
            for row in rows:
                vTable  = str(row[0])
                vType   = str(row[1])
                vStatus = str(row[2])

                sData   = 'table:'+vTable+',action:'+vType+',data: '

                try :
                    time.sleep(2)
                    conn = self.createSocket()
                    conn.sendall(sData+"\0")
                    self.delPollData(vTable,vType,vStatus)

                    if socket.timeout:
                        #log.debug("Database Socket Timedout")
                        continue
                    else:
                        data = conn.recv(1024)
                    continue

                    conn.close()
                    conn = None
                    time.sleep(2)
                except:
                    time.sleep(2)
                    e = sys.exc_info()[1]
                    print "Database Error: %s" %e
                    log.debug("Database Error: %s" %e)
                    conn = self.createSocket()
                    conn.sendall(sData+"\0")

                    if socket.timeout:
                        log.debug("Database Socket Except Timedout")
                        continue
                    else:
                        data = conn.recv(1024)
                    continue

                    conn.close()
                    conn = None
                    time.sleep(2)

            time.sleep(1)

    def connect(self):
        self.connection = MySQLdb.connect(host=self.dbHost,port=self.dbPort,user=self.dbUser,passwd=self.dbPass,db=self.dbName)
        self.cursor = self.connection.cursor()

    def commit(self):
        self.connection.commit()

    def disconnect(self):
        self.cursor.close()
        self.connection.commit()
        self.connection.close()

    def getData(self):
        sqlcmd = """SELECT DISTINCT NAME, TYPE, STATUS FROM SERVER_AUDIT"""
        try:
            self.connect()
            self.cursor.execute (sqlcmd)
            result =  self.cursor.fetchall()
            self.disconnect()
        except:
            e = sys.exc_info()[1]
            log.error("getData %s"%e, sys, traceback)
            sys.exit(e)
        return result

     def createSocket(self) :
        _cfgServer = cfg.Config().EchoServer()
        EchoHost  = _cfgServer.EchoServerHost
        EchoPort = int(float(str(_cfgServer.EchoServerPorts)))

        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        conn.settimeout(60.0)
        conn.connect((EchoHost, EchoPort))
        return conn

class pChecker(Process):
    def __init__(self):
        super(pChecker, self).__init__()
        self.is_stop = Event()
        self.is_stop.clear()

    def check_server(self, address, port):
        # Create a TCP socket
        s = socket.socket()
        try:
            s.connect((address, port))
            s.close()
            return True
        except:
            return False

    def createSocket(self) :
        _cfgServer = cfg.Config().EchoServer()
        EchoHost  = _cfgServer.EchoServerHost
        EchoPort = int(float(str(_cfgServer.EchoServerPorts)))

        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        conn.settimeout(60)
        conn.connect((EchoHost, EchoPort))
        return conn

    def run(self):
        print "pChecker pid %s" % self.pid
        while not self.is_stop.is_set():
            modem1 = self.check_server('XX.X.X.XXX', XXX)

            modem  = ''

            if modem1 != True :
                modem = "modem1:connect,"
            else:
                modem = "modem1:disconnect,"

            try :
                time.sleep(2)
                conn = self.createSocket()
                conn.sendall("[modem]"+modem[:-1]+"\0")
                #data = conn.recv(1024)

                if socket.timeout:
                    #log.debug("pChecker Socket Timedout")
                    continue
                else:
                    data = conn.recv(1024)
                continue

                conn.close()
                conn = None
                time.sleep(2)
            except:
                time.sleep(2)
                e = sys.exc_info()[1]
                log.error("pChecker %s"%e, sys, traceback)
                conn = self.createSocket()
                conn.sendall("[modem]"+modem[:-1]+"\0")
                #data = conn.recv(1024)

                if socket.timeout:
                    log.debug("pChecker Socket Timedout")
                    continue
                else:
                    data = conn.recv(1024)
                continue

                #print data
                conn.close()
                conn = None
                time.sleep(2)


class Server(Process):
    def __init__(self):
        super(Server, self).__init__()
        self.is_stop = Event()
        self.is_stop.clear()

    def run(self):
        print "Server pid %s" % self.pid

        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.server.bind((EchoHost,EchoPort))
        self.server.listen(64)
        self.input = [self.server]
        try:
            while not self.is_stop.is_set():

                inputready,outputready,exceptready = select.select(self.input,[],[])

                for s in inputready:

                    if s == self.server:
                        # handle the server socket
                        client, address = self.server.accept()
                        addrstr = '%s:%s' % (address[0],address[1])
                        ClientIP = str(address[0])
                        self.input.append(client)

                    elif s == sys.stdin:
                        # handle standard input
                        junk = sys.stdin.readline()
                        running = 0

                    else:
                        # handle all other sockets
                        try:
                            data = s.recv(1024)
                            #print "Send Data %s" %data
                        except IOError as e:
                            f = sys.exc_info()[1]
                            log.error("Server Error: %s" %f, sys, traceback)
                            if e.args[1].args[0].errno != errno.ECONNERSET:
                                raise

                        tempConn = self.input[1:len(self.input)]

                        if data:
                                for i in tempConn:
                                        i.send(data)
                                        if ClientIP != '10.0.1.2':
                                            log.info('See to Client: %s data: %s'%ClientIP,data)

                        else:
                            s.close()
                            self.input.remove(s)
            print "Server: exiting"
            log.info("Server: exiting")
        except:
            e = sys.exc_info()[1]
            log.error("Server Error: %s" %e, sys, traceback)
</code></pre>
