Hier ist der Code, mit dem ich als Basis arbeite. Wie kann ich dies ändern, um mein Endziel zu erreichen?
Code: Select all
# Client IP and Port configuration
HOST = '127.0.0.1' # Server's IP address (localhost)
PORT = 65432 # Port the server is listening on# Start the client
def start_client():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((HOST, PORT)) # Connect to the server
while True:
message = input("Enter your message (type 'exit' to quit): ")
if message.lower() == 'exit':
print("Closing the connection...")
break client_socket.sendall(message.encode()) # Send the message to the server
data = client_socket.recv(1024) # Receive the response from the server
print(f"Server response: {data.decode()}")
print("Connection terminated.")if __name__ == "__main__":
start_client()
Code: Select all
# Server IP and Port configuration
import socket
import threading
# Server IP and Port configuration
HOST = '10.9.0.7' # Server IP (localhost)
PORT = 4433 # Port for client connections# Function to manage client connections
def handle_client(conn, addr):
print(f"Connection established with {addr}.")
while True:
try:
data = conn.recv(1024) # Receive data from the client
if not data:
break # Terminate the connection if no data is received
print(f"Received from {addr}: {data.decode()}")
conn.sendall(f"Server response: {data.decode()}".encode()) # Send the received data back to the client
except ConnectionResetError:
print(f"Client {addr} has disconnected.")
break
conn.close()
print(f"Connection with {addr} closed.")# Start the server
def start_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Server listening on {HOST}:{PORT}...")
while True:
conn, addr = server_socket.accept() # Accept a client connection
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start() # Start a new thread for each client
print(f"Active connections: {threading.activeCount() - 1}")
if __name__ == "__main__":
start_server()
Mobile version