# TCP server example for IPv4
import socket
import sys
"""
This program is modified from an example (c)Python Software Foundation
that was posted at https://docs.python.org/3/library/socket.html
"""

HOST, PORT = "", 60000

def handle_client(socket, addr):
    try:
        socket.setblocking(True)
        socket.settimeout(10.0)
        data = socket.recv(2048)
        # 2048 is the maximum buffer size, the function return even with as little as 1 byte
        socket.sendall(data)
    except socket.Timeouterror:
        print("Incoming data timeout, exiting")

try:
    # Create a socket (SOCK_STREAM means a TCP socket)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Bind the socket to a particular port number (and perhaps to a network interface - HOST)
    server.bind( (HOST, PORT) )
    # Start the server
    server.listen(1)
except:
    server.close()
    print("could not open the server socket")
    sys.exit(1)

# serve forever
while 1:
    try:
        client_socket, client_address = server.accept()
        handle_client(client_socket, client_address)
    except:
        print("Problems while handling an incoming client: ", client_socket)
    finally:
        client_socket.close()