1

I build that server in Python , I need to serve only 1 user each time

import socket

class MyServer:
    def __init__(self, port):
        self.port = port
        
        
    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = ('0.0.0.0', self.port)
        sock.bind(server_address)
        sock.listen(1)


        while True:
            
            connection, client_address = sock.accept()
            try:
                while True:
                    data = connection.recv(1024)
                    print(len(data))
                
            finally:
                connection.close()

The problem is that when client disconnects from the server he can not reconnect to send data, because the code is in the inner loop and still print 0.

How can I put timeout for data = connection.recv(1024) for example 5 seconds , that if there is no data the server will wait for new connection?

vtable
  • 302
  • 2
  • 15

1 Answers1

0

You need to set a timeout for the socket by using the settimeout method. Note that when timeout occurs, a timeout exception is raised so that needs to be handled.

Shak
  • 418
  • 1
  • 4
  • 14