56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
import socket
|
|
import sys
|
|
|
|
# Configuration
|
|
HOST = '0.0.0.0' # Listen on all interfaces
|
|
PORT = 5588
|
|
|
|
def start_server():
|
|
try:
|
|
# Create a TCP/IP socket
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
# Bind the socket to the port
|
|
server_address = (HOST, PORT)
|
|
print(f'Starting server on {HOST}:{PORT}...')
|
|
sock.bind(server_address)
|
|
|
|
# Listen for incoming connections
|
|
sock.listen(1)
|
|
|
|
while True:
|
|
print('\nWaiting for a connection...')
|
|
connection, client_address = sock.accept()
|
|
|
|
try:
|
|
print(f'Connection from {client_address}')
|
|
|
|
# Receive the data in small chunks and retransmit it
|
|
while True:
|
|
try:
|
|
data = connection.recv(1024)
|
|
if data:
|
|
print(f'Received: {data.decode("utf-8", errors="ignore")}')
|
|
# Echo back
|
|
response = f"Server received: {len(data)} bytes"
|
|
connection.sendall(response.encode('utf-8'))
|
|
else:
|
|
print(f'No more data from {client_address}')
|
|
break
|
|
except ConnectionResetError:
|
|
print(f'Connection reset by {client_address}')
|
|
break
|
|
|
|
finally:
|
|
# Clean up the connection
|
|
connection.close()
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
except KeyboardInterrupt:
|
|
print("\nServer stopping...")
|
|
sys.exit(0)
|
|
|
|
if __name__ == "__main__":
|
|
start_server()
|