Comprensión de Sockets en Python y Comunicación Básica
Comencemos por entender qué son los sockets y cómo funcionan en Python.
¿Qué es un Socket?
Un socket es un punto final para enviar y recibir datos a través de una red. Piense en él como un punto de conexión virtual a través del cual fluye la comunicación de red. El módulo socket incorporado de Python proporciona las herramientas para crear, configurar y usar sockets para la comunicación de red.
Flujo de Comunicación de Socket Básico
La comunicación de socket típicamente sigue estos pasos:
- Crear un objeto socket
- Vincular el socket a una dirección (para servidores)
- Escuchar las conexiones entrantes (para servidores)
- Aceptar conexiones (para servidores) o conectarse a un servidor (para clientes)
- Enviar y recibir datos
- Cerrar el socket cuando se haya terminado
Creemos nuestro primer programa de socket simple para comprender mejor estos conceptos.
Creando su Primer Servidor Socket
Primero, creemos un servidor socket básico que escuche las conexiones y devuelva cualquier dato que reciba.
Abra el WebIDE y cree un nuevo archivo llamado server.py en el directorio /home/labex/project con el siguiente contenido:
import socket
## Define server address and port
HOST = '127.0.0.1' ## Standard loopback interface address (localhost)
PORT = 65432 ## Port to listen on (non-privileged ports are > 1023)
## Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket created successfully")
## Bind the socket to the specified address and port
server_socket.bind((HOST, PORT))
print(f"Socket bound to {HOST}:{PORT}")
## Listen for incoming connections
server_socket.listen(1)
print(f"Socket is listening for connections")
## Accept a connection
print(f"Waiting for a connection...")
connection, client_address = server_socket.accept()
print(f"Connected to client: {client_address}")
## Receive and echo data
try:
while True:
## Receive data from the client
data = connection.recv(1024)
if not data:
## If no data is received, the client has disconnected
print(f"Client disconnected")
break
print(f"Received: {data.decode('utf-8')}")
## Echo the data back to the client
connection.sendall(data)
print(f"Sent: {data.decode('utf-8')}")
finally:
## Clean up the connection
connection.close()
server_socket.close()
print(f"Socket closed")
Creando su Primer Cliente Socket
Ahora, creemos un cliente para conectarnos a nuestro servidor. Cree un nuevo archivo llamado client.py en el mismo directorio con el siguiente contenido:
import socket
## Define server address and port
HOST = '127.0.0.1' ## The server's hostname or IP address
PORT = 65432 ## The port used by the server
## Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket created successfully")
## Connect to the server
client_socket.connect((HOST, PORT))
print(f"Connected to server at {HOST}:{PORT}")
## Send and receive data
try:
## Send data to the server
message = "Hello, Server!"
client_socket.sendall(message.encode('utf-8'))
print(f"Sent: {message}")
## Receive data from the server
data = client_socket.recv(1024)
print(f"Received: {data.decode('utf-8')}")
finally:
## Clean up the connection
client_socket.close()
print(f"Socket closed")
Probando sus Programas Socket
Ahora, probemos nuestros programas socket. Abra dos ventanas de terminal en la máquina virtual LabEx.
En la primera terminal, ejecute el servidor:
cd ~/project
python3 server.py
Debería ver una salida similar a:
Socket created successfully
Socket bound to 127.0.0.1:65432
Socket is listening for connections
Waiting for a connection...
Mantenga el servidor en ejecución y abra una segunda terminal para ejecutar el cliente:
cd ~/project
python3 client.py
Debería ver una salida similar a:
Socket created successfully
Connected to server at 127.0.0.1:65432
Sent: Hello, Server!
Received: Hello, Server!
Socket closed
Y en la terminal del servidor, debería ver:
Connected to client: ('127.0.0.1', XXXXX)
Received: Hello, Server!
Sent: Hello, Server!
Client disconnected
Socket closed
¡Felicidades! Acaba de crear y probar su primera aplicación cliente-servidor basada en sockets en Python. Esto proporciona la base para comprender cómo funciona la comunicación de socket y cómo implementar el manejo de errores en los siguientes pasos.