python
Copy code
# server.py
import socket
def start_server():
# Define server host and port
host = '127.0.0.1' # 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)
# Bind the socket to the address and port
server_socket.bind((host, port))
# Enable the server to accept connections (max 1 queued connection)
server_socket.listen(1)
print(f"Server listening on {host}:{port}")
while True:
# Wait for a connection
client_socket, client_address = server_socket.accept()
print(f"Connection from {client_address} has been established.")
# Receive data from the client
data = client_socket.recv(1024).decode('utf-8')
print(f"Received from client: {data}")
# Send a response back to the client
response = "Hello, Client! Message received."
client_socket.send(response.encode('utf-8'))
# Close the connection
client_socket.close()
print(f"Connection with {client_address} closed.")
if __name__ == "__main__":
start_server()
python
Copy code
# client.py
import socket
def start_client():
# Define server host and port
host = '127.0.0.1' # Server address
port = 65432 # Server port
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the server
client_socket.connect((host, port))
print(f"Connected to server {host}:{port}")
# Send a message to the server
message = "Hello, Server!"
client_socket.send(message.encode('utf-8'))
# Receive a response from the server
response = client_socket.recv(1024).decode('utf-8')
print(f"Received from server: {response}")
except ConnectionError as e:
print(f"Connection error: {e}")
finally:
# Close the connection
client_socket.close()
if __name__ == "__main__":
start_client()