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?