Intentando limitar el numero de cliente que pueden usar el servidor

master
vicsash 7 months ago
parent ff3566fec7
commit 32655b8c32

@ -14,7 +14,7 @@ def get_ip_address():
return IP return IP
HOST = get_ip_address() HOST = get_ip_address()
PORT = 2005 PORT = 2002
while True: while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
@ -22,22 +22,27 @@ while True:
try: try:
s.connect(server_address) s.connect(server_address)
except ConnectionRefusedError: except ConnectionRefusedError:
print("Connection refused, try again later.") print("Conexión rechazada, intente más tarde.")
sys.exit() # Terminate the program sys.exit()
# Send a message immediately after connecting
message = "Conectando!" message = "Conectando!"
print('{!r}'.format(message)) print('{!r}'.format(message))
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
print('Esperando la respuesta') data = s.recv(1024)
while True: # Keep the connection open until the user enters a command print("Received data from server: " + data.decode('utf-8'))
if data.decode('utf-8') == "Maximo numero de conexiones alcanzado. Por favor intente mas tarde.":
print("Conexiones máximas alcanzadas. Por favor intente más tarde.")
sys.exit()
while True:
command = input("Entra comando (retirar o 'exit' para salir): ") command = input("Entra comando (retirar o 'exit' para salir): ")
if command.lower() == 'exit': if command.lower() == 'exit':
s.sendall(command.encode('utf-8'))
time.sleep(1)
break break
elif command.lower() == 'retirar': elif command.lower() == 'retirar':
amount = input("Entera la cantidad de dinero: ") amount = input("Entera la cantidad de dinero: ")
message = f"{command} {amount}" message = f"{command} {amount}"
else: else:
print("Comando no reconocido") print("Comando no reconocido")
message = command # Send the unrecognized command to the server message = command
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
break

@ -14,7 +14,7 @@ def get_ip_address():
return IP return IP
HOST = get_ip_address() HOST = get_ip_address()
PORT = 2005 PORT = 2002
while True: while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
@ -22,22 +22,27 @@ while True:
try: try:
s.connect(server_address) s.connect(server_address)
except ConnectionRefusedError: except ConnectionRefusedError:
print("Connection refused, try again later.") print("Conexión rechazada, intente más tarde.")
sys.exit() # Terminate the program sys.exit()
# Send a message immediately after connecting
message = "Conectando!" message = "Conectando!"
print('{!r}'.format(message)) print('{!r}'.format(message))
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
print('Esperando la respuesta') data = s.recv(1024)
while True: # Keep the connection open until the user enters a command print("Received data from server: " + data.decode('utf-8'))
if data.decode('utf-8') == "Maximo numero de conexiones alcanzado. Por favor intente mas tarde.":
print("Conexiones máximas alcanzadas. Por favor intente más tarde.")
sys.exit()
while True:
command = input("Entra comando (retirar o 'exit' para salir): ") command = input("Entra comando (retirar o 'exit' para salir): ")
if command.lower() == 'exit': if command.lower() == 'exit':
s.sendall(command.encode('utf-8'))
time.sleep(1)
break break
elif command.lower() == 'retirar': elif command.lower() == 'retirar':
amount = input("Entera la cantidad de dinero: ") amount = input("Entera la cantidad de dinero: ")
message = f"{command} {amount}" message = f"{command} {amount}"
else: else:
print("Comando no reconocido") print("Comando no reconocido")
message = command # Send the unrecognized command to the server message = command
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
break

@ -14,7 +14,7 @@ def get_ip_address():
return IP return IP
HOST = get_ip_address() HOST = get_ip_address()
PORT = 2005 PORT = 2002
while True: while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
@ -22,22 +22,27 @@ while True:
try: try:
s.connect(server_address) s.connect(server_address)
except ConnectionRefusedError: except ConnectionRefusedError:
print("Connection refused, try again later.") print("Conexión rechazada, intente más tarde.")
sys.exit() # Terminate the program sys.exit()
# Send a message immediately after connecting
message = "Conectando!" message = "Conectando!"
print('{!r}'.format(message)) print('{!r}'.format(message))
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
print('Esperando la respuesta') data = s.recv(1024)
while True: # Keep the connection open until the user enters a command print("Received data from server: " + data.decode('utf-8'))
if data.decode('utf-8') == "Maximo numero de conexiones alcanzado. Por favor intente mas tarde.":
print("Conexiones máximas alcanzadas. Por favor intente más tarde.")
sys.exit()
while True:
command = input("Entra comando (retirar o 'exit' para salir): ") command = input("Entra comando (retirar o 'exit' para salir): ")
if command.lower() == 'exit': if command.lower() == 'exit':
s.sendall(command.encode('utf-8'))
time.sleep(1)
break break
elif command.lower() == 'retirar': elif command.lower() == 'retirar':
amount = input("Entera la cantidad de dinero: ") amount = input("Entera la cantidad de dinero: ")
message = f"{command} {amount}" message = f"{command} {amount}"
else: else:
print("Comando no reconocido") print("Comando no reconocido")
message = command # Send the unrecognized command to the server message = command
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
break

@ -14,7 +14,7 @@ def get_ip_address():
return IP return IP
HOST = get_ip_address() HOST = get_ip_address()
PORT = 2005 PORT = 2002
while True: while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
@ -22,22 +22,27 @@ while True:
try: try:
s.connect(server_address) s.connect(server_address)
except ConnectionRefusedError: except ConnectionRefusedError:
print("Connection refused, try again later.") print("Conexión rechazada, intente más tarde.")
sys.exit() # Terminate the program sys.exit()
# Send a message immediately after connecting
message = "Conectando!" message = "Conectando!"
print('{!r}'.format(message)) print('{!r}'.format(message))
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
print('Esperando la respuesta') data = s.recv(1024)
while True: # Keep the connection open until the user enters a command print("Received data from server: " + data.decode('utf-8'))
if data.decode('utf-8') == "Maximo numero de conexiones alcanzado. Por favor intente mas tarde.":
print("Conexiones máximas alcanzadas. Por favor intente más tarde.")
sys.exit()
while True:
command = input("Entra comando (retirar o 'exit' para salir): ") command = input("Entra comando (retirar o 'exit' para salir): ")
if command.lower() == 'exit': if command.lower() == 'exit':
s.sendall(command.encode('utf-8'))
time.sleep(1)
break break
elif command.lower() == 'retirar': elif command.lower() == 'retirar':
amount = input("Entera la cantidad de dinero: ") amount = input("Entera la cantidad de dinero: ")
message = f"{command} {amount}" message = f"{command} {amount}"
else: else:
print("Comando no reconocido") print("Comando no reconocido")
message = command # Send the unrecognized command to the server message = command
s.sendall(message.encode('utf-8')) s.sendall(message.encode('utf-8'))
break

@ -1,8 +1,9 @@
import socket import socket
import sys
import threading import threading
HOST = '' HOST = ''
PORT = 2005 PORT = 2002
MAX_CONNECTIONS = 3 MAX_CONNECTIONS = 3
MAX_DINERO = 120000 MAX_DINERO = 120000
connections = 0 connections = 0
@ -11,21 +12,29 @@ max_connections_reached = False # Add a flag for max connections reached
def handle_client(client_socket, addr): def handle_client(client_socket, addr):
global connections global connections
global MAX_DINERO global MAX_DINERO
global max_connections_reached # Access the global flag
print(f"cliente conectado {addr})") print(f"cliente conectado {addr})")
connections += 1 connections += 1
if connections < MAX_CONNECTIONS: if connections > MAX_CONNECTIONS:
max_connections_reached = False # Reset the flag when connections drop below max response = "Maximo numero de conexiones alcanzado. Por favor intente mas tarde."
client_socket.sendall(response.encode('utf-8'))
client_socket.close()
return
print(f"Conexiones activas: {connections}") print(f"Conexiones activas: {connections}")
client_socket.settimeout(60) # Set a timeout of 60 seconds try:
while True: while True:
try: try:
datos = client_socket.recv(1024) datos = client_socket.recv(1024)
except ConnectionResetError:
print("Connection was closed by the client.")
break
if not datos: if not datos:
print("No data received from client. Closing connection.") print("No data received from client. Closing connection.")
break # Close the connection when no data is received break
decoded_data = datos.decode('utf-8') decoded_data = datos.decode('utf-8')
if ' ' in decoded_data: if decoded_data.lower() == 'conectando!':
response = "Connection successful!"
client_socket.sendall(response.encode('utf-8'))
elif ' ' in decoded_data:
command, amount = decoded_data.split() command, amount = decoded_data.split()
amount = int(amount) amount = int(amount)
if command.lower() == 'retirar': if command.lower() == 'retirar':
@ -37,25 +46,25 @@ def handle_client(client_socket, addr):
else: else:
response = "Saldo insuficiente por favor intente mas tarde." response = "Saldo insuficiente por favor intente mas tarde."
client_socket.sendall(response.encode('utf-8')) client_socket.sendall(response.encode('utf-8'))
elif command.lower() == 'exit':
break
else: else:
print(f"Received unexpected data: {decoded_data}") print(f"Received unexpected data: {decoded_data}")
except socket.timeout: except socket.timeout:
print("Client did not send data within the timeout period.") print("Client did not send data within the timeout period.")
finally:
connections -= 1 connections -= 1
print(f"Conexiones activas: {connections}") print(f"Conexiones activas: {connections}")
client_socket.close() client_socket.close()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: while True:
s_addr = (HOST, PORT) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(s_addr) server_address = (HOST, PORT)
s.bind(server_address)
s.listen(MAX_CONNECTIONS) s.listen(MAX_CONNECTIONS)
while True: while True:
if connections >= MAX_CONNECTIONS: if connections < MAX_CONNECTIONS:
if not max_connections_reached: # Only print the message if the flag is False
print('Maximo de conexiones alcanzado, esperando a que se libere una conexion.')
max_connections_reached = True # Set the flag to True after printing the message
continue
client_socket, addr = s.accept() client_socket, addr = s.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket, addr)) client_thread = threading.Thread(target=handle_client, args=(client_socket, addr))
client_thread.daemon = True
client_thread.start() client_thread.start()

Loading…
Cancel
Save

Powered by INFORMATICA.FP.EDU.ES.