0

I have a very basic socket script which sends a single message to clients.

Part of server script :

while True:
    con,address=s.accept()
    con.send("Hello from server".encode())
    con.close()
s.close()

Part of client script :

message = s.recv(5)
while message:
    print("Message", message.decode())
    sleep(1)
    message=s.recv(5)
s.close()

I start 2 clients. They both prints the message (5 bytes at a time), then close.

However the server remains open, because it is still waiting for clients.

What is the correct way to exit the server while True loop ?

trogne
  • 3,402
  • 3
  • 33
  • 50

1 Answers1

1

You have to specify on what condition you want your server to exit. Usually a server is programmed like a daemon, i.e., run indefinitely. In python, you already have a way to break the infinite while loop -- Ctrl-C to trigger a keyboard exception. Otherwise, think of the following:

  1. After N clients handled, break inside the loop. You will need to have a counter and keep track of the clients handled
  2. On some POSIX signal, such as the answer in How do I capture SIGINT in Python?, and usually this is the way daemons do to terminate nicely

By the way, your server code may need rewrite: You currently only handle one client at a time without parallel processing. It will very easy run into head-of-line blocking issues when you have many clients.

adrtam
  • 6,991
  • 2
  • 12
  • 27