import socket
import time
import random

# the number of bytes for representing the length of the request/response message
SIZE_REQUEST_LENGTH = 1

# the number of digits for representing the length of the response message
NUM_DIGITS_LENGTH_FIELD = 2

# use python string formatitng to add heading zeros
RESPONSE_LENGTH_FIELD_FORMAT = '%0' + str(NUM_DIGITS_LENGTH_FIELD) + 'd'

HOST = '127.0.0.1'
PORT = 1729
ADDR = (HOST, PORT)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(ADDR)

s.listen(1)

(conn, addr) = s.accept()

while True:
    request_length_field = int(conn.recv(SIZE_REQUEST_LENGTH))
    
    # recive the request of the client
    request = conn.recv(request_length_field)
    if not request:
        break

    print request

    # process the request of the client and generate response message
    if request == 'TIME':
        response_message = time.ctime()
    
    elif request == 'NAME':
        response_message = 'Yosske HaSharat'
    
    elif request == 'RAND':
        response_message = str(random.randint(1, 10))
    
    elif request == 'EXIT':
        break
    
    elif not request:
        break
    
    else:
        response_message = 'ERROR!'

    # calculate the response message length
    response_length = len(response_message)

    # add heading zeros to response length field
    response_length_field = RESPONSE_LENGTH_FIELD_FORMAT % response_length

    # concatenate the response length field to the response message
    response_data = response_length_field + response_message

    conn.send(response_data)

conn.close()
s.close()
