Skip to content
Snippets Groups Projects
Commit 03bf6bae authored by Katharina's avatar Katharina
Browse files

election

parent 7518ca22
No related branches found
No related tags found
No related merge requests found
No preview for this file type
...@@ -5,13 +5,10 @@ import uuid ...@@ -5,13 +5,10 @@ import uuid
broadcast_ip = '255.255.255.255' broadcast_ip = '255.255.255.255'
broadcast_port = 55555 broadcast_port = 55555
# create unique server-ID # Create a unique server ID
server_id = str(uuid.uuid4()) server_id = str(uuid.uuid4())
# Set to store UUIDs of other servers # Create server socket for broadcasting
server_uuids = set()
# create server-socket for broadcast
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
...@@ -19,71 +16,74 @@ server_socket.bind(('', broadcast_port)) ...@@ -19,71 +16,74 @@ server_socket.bind(('', broadcast_port))
print(f"Server is running with ID {server_id} and broadcasting on port {broadcast_port}...") print(f"Server is running with ID {server_id} and broadcasting on port {broadcast_port}...")
#broadcast function # Store the current leader's ID
current_leader = None
# Broadcast function
def broadcast(message): def broadcast(message):
"""sends messages to all server-IDs in the network""" """Send messages to all other nodes in the network."""
full_message = f"[{server_id}] {message}".encode() full_message = f"[{server_id}] {message}".encode()
server_socket.sendto(full_message, (broadcast_ip, broadcast_port)) server_socket.sendto(full_message, (broadcast_ip, broadcast_port))
#listener function # Listener function
def listen(): def listen():
"""receives messages from clients and broadcast them.""" """Receive messages and implement LCR logic."""
global current_leader
while True: while True:
try: try:
message, client_address = server_socket.recvfrom(4096) message, client_address = server_socket.recvfrom(4096)
decoded_message = message.decode() decoded_message = message.decode()
# Extract UUID from the message # Extract sender UUID and payload
if decoded_message.startswith("[") and "]" in decoded_message: if decoded_message.startswith("[") and "]" in decoded_message:
sender_uuid = decoded_message.split("]")[0][1:] sender_uuid = decoded_message.split("]")[0][1:]
payload = decoded_message.split("]")[1].strip()
# Ignore messages from self # Ignore messages from self
if sender_uuid == server_id: if sender_uuid == server_id:
continue continue
# Add the UUID to the set if it's not already known # LCR logic
if sender_uuid not in server_uuids: if payload == "START_ELECTION":
server_uuids.add(sender_uuid) print(f"Received election start from {sender_uuid}")
print(f"Discovered new server UUID: {sender_uuid} and server set: {server_uuids}") if sender_uuid > server_id:
# print(server_uuids) # Forward the sender's ID
broadcast(f"START_ELECTION {sender_uuid}")
#checks if the message containts the string "entered" elif sender_uuid < server_id:
if decoded_message.__contains__("entered"): # Send own ID into the ring
print(f"{client_address} entered the chat.") broadcast(f"START_ELECTION {server_id}")
else:
# If sender_uuid == server_id, we are the leader
current_leader = server_id
broadcast(f"LEADER {server_id}")
print(f"I am the leader: {server_id}")
elif payload.startswith("LEADER"):
leader_id = payload.split(" ")[1]
current_leader = leader_id
print(f"Leader has been elected: {leader_id}")
print(f"Received from {client_address}: {decoded_message}")
broadcast(decoded_message)
#exceptions
except socket.error as e: except socket.error as e:
print(f"An error occurred: {e}") print(f"An error occurred: {e}")
break break
#does not work
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nServer wird beendet...") print("\nShutting down server...")
break break
# Start the election
def start_election():
"""Initiate the LCR election process."""
print("Starting election...")
broadcast(f"START_ELECTION {server_id}")
if __name__ == "__main__": if __name__ == "__main__":
#main thread # Start the listener thread
listen_thread = threading.Thread(target=listen) listen_thread = threading.Thread(target=listen)
#listen_thread.daemon = True
listen_thread.start() listen_thread.start()
#print(listen_thread.is_alive())
#listen()
# Example of broadcasting your UUID periodically (optional) # Start election after a short delay
def periodic_broadcast():
import time import time
while True: time.sleep(2)
try: start_election()
broadcast("Server is running")
time.sleep(10) # Broadcast every 5 seconds
except KeyboardInterrupt:
break
broadcast_thread = threading.Thread(target=periodic_broadcast)
broadcast_thread.daemon = True # Stop when main thread stops
broadcast_thread.start()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment