3

I'm having a problem with a python script I didn't write myself and I'm completely new to python. The script runs on a Raspberry Pi and listens on port 8080 (socket). A client can send a command such as "reboot()". The problem is that when a client closes the connection, the script does no longer accept new connections and execute the command.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", 8080))
s.listen(1)
conn = s.accept()

while True:
 data = conn[0].recv(1024)
 if data:
    command = ""
    args = ""
    if "(" in data and ")" in data:
        command = data[:data.index("(")]
        args = data[data.index("(") + 1:data.index(")")]
    if "," in args:
        arglist = args.split(",")
    else:
        arglist = args

    if command == "reboot":
        os.system("reboot")
    elif command == "shutdown":
        os.system("shutdown -h now")
    elif command == "reset":
        obja.reset()
        objb.reset()
    else:
        conn[0].sendall("Command doesn't exist!")

The script is run at startup and does not terminate. The last line here is also the last line in the original script. There is some more code above the lines I posted, but I don't think it's relevant for the socket problem. I tried putting the first 5 lines in the While-Loop, but that doesn't work. How should I re-write the code so that it goes on when the client closes the connection? Any help is very welcome.

Peter

Peter
  • 31
  • 1
  • 3

1 Answers1

4

The code you need to put in a while loop begins with conn = s.accept().

You only want to set up the socket and call bind/listen once. You do, however, want to catch exceptions such as a ConnectionClosed and go back to calling accept again when they happen. To do this you will want to wrap the body of the new while loop you add in a try/except. The except block will need to catch any type of exception that occurs when the client loses its connection.

Good luck and happy coding!

Borealid
  • 95,191
  • 9
  • 106
  • 122