P
P
pavelpasha2018-10-12 13:33:26
Python
pavelpasha, 2018-10-12 13:33:26

Why is the connection to the server not being restored after a long break?

On the remote raspbury, the code that collects and transmits data to the server is spinning. When the connection is broken, there is an endless reconnection, but if there was no connection for a very long time, for example, about a day, then the reconnection procedure is blocked somewhere or hangs. It's hard to understand what exactly happened. I connect via SSH, I see the code running, I see how it collects data, but I don't see any attempts to connect to the server. (data collection and sending work in different threads). If the gap was not long - a couple of hours, let's say, then there is no problem.

def connectToServer ():
    print("Server: connecting")
    global ServerSock
    try:
        ServerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ServerSock.settimeout(10)
        ServerSock.connect((ServerHost, ServerPort))
        ServerSock.settimeout(10)
        print("Server: connected")
    except:
        print("error occured")
        ServerSock.close()
        time.sleep(5)
        connectToServer()



def runServerSending ():
    connectToServer()
    while True:
            try:
                ServerSock.sendall(json.dumps(this.__dict__).encode())
                answer = ServerSock.recv(1024)
                if not answer:
                    raise Exception('Server socket error')
            except:
                print("Server: send data error")
                ServerSock.close()
                connectToServer()
            time.sleep(10)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Meonn, 2018-10-12
@pavelpasha

Perhaps you have a buffer overflow due to a recurrent call to connectToServer ()

def connectToServer ():
    ....
    except:
        print("error occured")
        ServerSock.close()
        time.sleep(5)
        connectToServer()

Try like this:
def connectToServer ():
    print("Server: connecting")
    global ServerSock
    connected = False
    while not connected:
        try:
            ServerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            ServerSock.settimeout(10)
            ServerSock.connect((ServerHost, ServerPort))
            ServerSock.settimeout(10)
            print("Server: connected")
            connected = True
        except:
            print("error occured")
            ServerSock.close()
            time.sleep(5)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question