Skip to content
Snippets Groups Projects
Commit a7cb74d4 authored by Michelle Fahrner's avatar Michelle Fahrner
Browse files

Upload New File

parent f6721de1
No related branches found
No related tags found
1 merge request!1Feat/finalfinal
import socket
import multiprocessing
import uuid
import time
import threading
import os
from multiprocessing import Manager
from collections import deque
myuuid = uuid.uuid4() #Creating a unique ip Adress using uuid4
my_ID = str(myuuid) #Creating a unique ip Adress using uuid4
# Broadcast IP and port configuration
broadcast_ip = '255.255.255.255'
client_broadcast_port = 55555
ip_address = "127.0.0.1"
# Socket setup for client broadcast
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create a UDP socket
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # Enable broadcast mode
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow address reuse
server_socket.bind(('', client_broadcast_port)) # Bind to the broadcast port
def broadcast(message):
"""
Sends a message to all participants in the network via broadcast.
"""
full_message = f"{message}".encode() # Encode the message
server_socket.sendto(full_message, (broadcast_ip, client_broadcast_port)) # Send the broadcast message
def listen_client():
"""
Listens for messages from clients, processes them, and broadcasts them to other participants.
"""
received_message_uuid = set() # Track processed messages using a set of message UUIDs
MAX_MESSAGES = 3 # Limit on the number of messages stored in the queue
message_queue = deque(maxlen=MAX_MESSAGES) # Queue to store recently processed messages
while True:
try:
message, client_address = server_socket.recvfrom(4096) # Receive a message from a client
decoded_message = message.decode() # Decode the message
message_id = decoded_message.split(":")[0] # Extract message UUID
if message_id in received_message_uuid: # check if it's already processed
continue # Skip if the message was already processed
message_queue.append(message_id) # mark message as proccessed
received_message_uuid.add(message_id)
# Remove the oldest message from the set if the queue reaches its limit
if len(message_queue) == MAX_MESSAGES:
removed_id = message_queue.popleft()
received_message_uuid.remove(removed_id)
print("erhaltene msg uuid:", received_message_uuid)
# Ignore messages originating from this server#################################################### Brauchen wir das??? Ich glaube nicht
if decoded_message.startswith(f"{my_ID}"):
continue # if...ignores it
# Check if the message contains the string "entered"
if decoded_message.__contains__("entered"):
print(f"{client_address} entered the chat.") #client_address is the nickname
# Log the received message
print(f"Received from {client_address}: {decoded_message}")
broadcast(decoded_message) # Broadcast the message to other participants
except socket.error as e: # Handle socket errors
print(f"An error occurred: {e}")
break
except KeyboardInterrupt: # Handle server shutdown via keyboard interrupt ????? Funktioniert das??
print("\nShutting down server...")
break
#**************************************Main function*************************************************
if __name__ == "__main__":
multiprocessing.freeze_support() # Ensure multiprocessing works across platforms
print(f"Script started with PID: {os.getpid()}") # Print the process ID of the script Brauchen wir das???????
print(f"Server is running with IP {ip_address} and broadcasting on port {client_broadcast_port}...")
listener_client_process = multiprocessing.Process(target=listen_client) # Create a process to listen for client messages
try:
listener_client_process.start() # Start the client listener process
except KeyboardInterrupt:
print("\nShutting down server...")
listener_client_process.terminate() # Terminate the listener process
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment