Serie: sockets
python
72 líneas
· Actualizado 2026-02-03
01-basic-tcp-server.py
sockets/examples/python/01-basic-tcp-server.py
#!/usr/bin/env python3
"""
Basic TCP Echo Server
A simple TCP server that echoes back whatever it receives.
This is the simplest possible TCP server implementation.
"""
import socket
# Configuration
HOST = 'localhost'
PORT = 8080
def main():
# Create TCP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Allow reuse of address (helpful for testing)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
# Bind socket to address
server.bind((HOST, PORT))
print(f"Server bound to {HOST}:{PORT}")
# Listen for connections (max 5 pending)
server.listen(5)
print(f"Server listening on {HOST}:{PORT}...")
print("Press Ctrl+C to stop")
while True:
# Accept incoming connection (blocks until client connects)
client, address = server.accept()
print(f"\nConnection from {address}")
try:
# Receive data from client
data = client.recv(1024) # Receive up to 1024 bytes
if data:
message = data.decode('utf-8')
print(f"Received: {message}")
# Echo data back to client
client.sendall(data)
print(f"Echoed: {message}")
else:
print("Client closed connection")
except Exception as e:
print(f"Error handling client: {e}")
finally:
# Close client connection
client.close()
print(f"Connection to {address} closed")
except KeyboardInterrupt:
print("\n\nShutting down server...")
except Exception as e:
print(f"Server error: {e}")
finally:
# Close server socket
server.close()
print("Server closed")
if __name__ == '__main__':
main()
Artículos relacionados
sockets
c
Actualizado 2026-02-05
01-basic-tcp-server.c
01-basic-tcp-server.c — c source code from the sockets learning materials (sockets/examples/c/01-basic-tcp-server.c).
Leer artículo →
sockets
c
Actualizado 2026-02-05
02-basic-tcp-client.c
02-basic-tcp-client.c — c source code from the sockets learning materials (sockets/examples/c/02-basic-tcp-client.c).
Leer artículo →
sockets
c
Actualizado 2026-02-05
03-basic-udp-server.c
03-basic-udp-server.c — c source code from the sockets learning materials (sockets/examples/c/03-basic-udp-server.c).
Leer artículo →
sockets
c
Actualizado 2026-02-05
04-basic-udp-client.c
04-basic-udp-client.c — c source code from the sockets learning materials (sockets/examples/c/04-basic-udp-client.c).
Leer artículo →
sockets
c
Actualizado 2026-02-05
05-https-client.c
05-https-client.c — c source code from the sockets learning materials (sockets/examples/c/05-https-client.c).
Leer artículo →
sockets
c
Actualizado 2026-02-05
06-domain-to-ip.c
06-domain-to-ip.c — c source code from the sockets learning materials (sockets/examples/c/06-domain-to-ip.c).
Leer artículo →