import socket
import random
import string
import base64
import time

def rand_str():
    length = 10
    letters = string.ascii_lowercase
    for i in range(length):
        result_str = ''.join(random.choice(letters) for i in range(length))
    print('random string generated = ',result_str)
    return result_str

def base64converter(the_string):
    return str(base64.b64encode(bytes(the_string, 'utf-8')))


port = 5000 #the port
socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #create socket object
socket.bind(('127.0.0.1', port)) #Bind the socket to address
socket.listen(1) #listen only one connection
connection, ip = socket.accept() #accept any income connection

start_time = int(round(time.time() * 1000))

print('INCOMING CONNECTION FROM:', str(ip))
#generate random string
random_string = rand_str()
#decode the string into base64
msg = str(base64converter(random_string).replace('\'',''))[1:]
print('we will send (msg after encoding) :',msg)
#send it, we must send it as a bytes
connection.send(bytes(msg.encode()))

#receive the replay from the client
replay = str(connection.recv(1024)).replace('\'','')[1:] ####u can use .decode('utf-8')####
print('The replay is :',replay)

end_time = int(round(time.time() * 1000))
total_time = end_time - start_time

if (random_string == replay):
    print('You got it!!')
    print('Time taken',total_time,'ms')
else:
    print('You failed!!')
    print('Time taken', total_time, 'ms')

connection.close()