1

I have the following Socket Server to run in a Raspberry.

I can connect to it, send commands and it replies the command.

Now I want that when I send the command RESET the Socket gets disconnected and the Raspberry returns to a Listening state, accepting a new connection.

However it seems that the address is not properly liberated and the OS throws an "Address already in use" exception.

Reconnecting....
OSError: [Errno 98] Address already in use


import socket
class SocketController:
    def __init__(self):
        self.s = None
        self.conn = None
        self.address = None

    def connect(self):
        host = ''
        port = 5560
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((host, port))
        self.s.listen(1)
        self.conn, self.address = self.s.accept()
        

    def disconnect(self):
        self.conn.close()
        self.s.close()

    def rx(self):
        data = self.conn.recv(1024).decode('utf-8')
        if data == "RESET":
            self.disconnect()
            print("Reconnecting....")
            self.connect()
        else:
            self.conn.sendall(str.encode(data))

if __name__ == '__main__':
    s = SocketController()
    s.connect()
    while True:
        rxData = s.rx()

What is the proper way of closing the connection and getting back to listening?

1 Answers1

0

You should tell to reuse the socket as it is marked as used until the end of you process.

You can do this easily by adding this after creating your socket and before the bind:

self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

You can find a full explanation in this comment

Cyrille Pontvieux
  • 2,356
  • 1
  • 21
  • 29