LABORATORIO Cliente/Servidor

4. Cliente codigo

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)

def mostrar_menu(opciones):
    print('Seleccione una opción:')
    for clave in sorted(opciones):
        print(f' {clave}) {opciones[clave][0]}')


def leer_opcion(opciones):
    while (a := input('Opción: ')) not in opciones:
        print('Opción incorrecta, vuelva a intentarlo.')
    return a


def ejecutar_opcion(opcion, opciones):
    opciones[opcion][1]()


def generar_menu(opciones, opcion_salida):
    opcion = None
    while opcion != opcion_salida:
        mostrar_menu(opciones)
        opcion = leer_opcion(opciones)
        ejecutar_opcion(opcion, opciones)
        print()


def menu_principal():
    opciones = {
        '1': ('Conectar socket', accion1),
        '2': ('Enviar mensaje simple', accion2),
        '3': ('Enviar mensaje personalizado', accion3),
        '4': ('Cerrar socket', accion4),
        '5': ('Terminar socket', accion5),
        '6': ('Salir', salir)
    }
    generar_menu(opciones, '6')


def accion1():
    print('connecting to {} port {}'.format(*server_address))
    sock.connect(server_address)

def accion2():
    message = b'hola mundo'
    print('sending {!r}'.format(message))
    sock.sendall(message)

def accion3():
    message = bytes(input("Ingrese texto: "), 'utf-8')
    print('sending {!r}'.format(message))
    sock.sendall(message)

def accion4():
    print('Shutdown socket')
    sock.shutdown(socket.SHUT_RDWR)
    sock.close()
exit()
    
def accion5():
    print('Close socket')
    sock.close()
    exit()
    
def salir():
    print('Saliendo')


if __name__ == '__main__':
    menu_principal()