Alle Dateien aus dem Pythonkurs
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.0 KiB

2 years ago
#! /usr/bin/python3
import socket
import threading
from network import __ADDRESSLOCAL__
2 years ago
# Server-Socket aufbauen
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Socket an unsere Server-Adresse binden
server.bind(__ADDRESSLOCAL__)
2 years ago
# Set mit den verbundenen Clients
clients = set()
# Locks für den Zugriff auf das Set
clients_lock = threading.Lock()
# Unsere Arbeitsmethode: rekursive Fibonacci-Reihe
def fib(n):
# Rekursionsbedingung
if n in [0,1]:
return 1
else:
# Rekursionsaufruf
return fib(n-1) + fib(n-2)
#bearbeitet eine eingehende Connection annehmen, pro Client ein seperater Thread
def handle_connection(conn,addr):
print(f"[NEW CONNECTION] {addr} Connected")
try:
connected = True
while connected:
msg = conn.recv(64).decode('utf-8')
print(f'[RECEIVED] {msg}')
if not msg:
break
else:
if msg.startswith('fib:'):
element = int(msg[4:])
fibo = fib(element)
print(f'[SENDING] fib({element})={fibo}')
# Ergebnis an Client senden.
with clients_lock:
for c in clients:
c.sendall(f'{fibo}'.encode('utf-8'))
else:
pass
if msg == 'quit':
print('[DISCONNECT]')
connected = False
# with clients_lock:
# for c in clients:
# c.sendall(f"[{addr}] {msg}".encode('utf-8'))
finally:
# Clientverbindung abbauen und aus Set entfernen.
with clients_lock:
clients.remove(conn)
conn.close()
# Start des Servers
def start():
print('[SERVER STARTED]!')
# Horchen nach eingehender Verbindung
server.listen()
while True:
# Neue Verbindung annehmen
conn, addr = server.accept()
# Neuen Client in Set aufnehmen
with clients_lock:
print(f'[ADDING CONNECTION] {conn}')
clients.add(conn)
#Thread zur Bearbeitung des Requests starten.
thread = threading.Thread(target=handle_connection, args=(conn, addr))
thread.start()
#Hauptprogramm: Serverstart einleiten
if __name__ == '__main__':
start()