Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
D
Distributed-Systems
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Katharina Willig
Distributed-Systems
Commits
9b1822c2
Commit
9b1822c2
authored
6 months ago
by
Katharina
Browse files
Options
Downloads
Patches
Plain Diff
add server handling to client
parent
7f267d83
Loading
Loading
No related merge requests found
Changes
3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
2024-12-22_Server_V4.py
+16
-4
16 additions, 4 deletions
2024-12-22_Server_V4.py
2025-01-01_Client_V4.py
+60
-12
60 additions, 12 deletions
2025-01-01_Client_V4.py
nickname.py
+28
-0
28 additions, 0 deletions
nickname.py
with
104 additions
and
16 deletions
2024-12-22_Server_V4.py
+
16
−
4
View file @
9b1822c2
...
@@ -22,8 +22,8 @@ broadcast_ip = "255.255.255.255" #Broadcast-adress in the Network
...
@@ -22,8 +22,8 @@ broadcast_ip = "255.255.255.255" #Broadcast-adress in the Network
enter_port
=
12348
#Port that is used for the discovery of new server participants
enter_port
=
12348
#Port that is used for the discovery of new server participants
ringport
=
12343
ringport
=
12343
election_port
=
12345
election_port
=
12345
client_broadcast_port
=
55555
client_broadcast_port
=
55555
#client sends, server listens
client_broadcast_port2
=
33333
client_broadcast_port2
=
33333
#server sends, client listens
acknowledgement_port
=
22222
acknowledgement_port
=
22222
heartbeat_port
=
44444
heartbeat_port
=
44444
heartbeat_ip
=
"
255.255.255.0
"
heartbeat_ip
=
"
255.255.255.0
"
...
@@ -343,13 +343,26 @@ def listen_client():
...
@@ -343,13 +343,26 @@ def listen_client():
last_three_messages
.
append
(
decoded_message
)
# Store the message for Leader heartbeat
last_three_messages
.
append
(
decoded_message
)
# Store the message for Leader heartbeat
#print(f"Message stored: {last_three_messages}")
#print(f"Message stored: {last_three_messages}")
message_id
=
decoded_message
.
split
(
"
:
"
)[
0
]
# Extract the unique message ID (UUID) from the decoded message
message_id
=
decoded_message
.
split
(
"
:
"
)[
0
]
# Extract the unique message ID (UUID) from the decoded message
if
message_id
in
processed_message_ids
:
# Check if the message has already been processed
if
message_id
in
processed_message_ids
:
# Check if the message has already been processed
continue
# Skip if the message was already processed
continue
# Skip if the message was already processed
# send acknowledgement to client
if
message_id
not
in
processed_message_ids
:
#print("heres the received message")
answer
=
f
"
received
"
.
encode
()
server_socket
.
sendto
(
answer
,
(
broadcast_ip
,
client_broadcast_port2
))
#?????
#if decoded_message.__contains__("server?"):
# server_socket.sendto(answer, (broadcast_ip, client_broadcast_port2))
hold_back_queue
.
append
((
message_id
,
decoded_message
))
# Add the message to the hold-back queue
hold_back_queue
.
append
((
message_id
,
decoded_message
))
# Add the message to the hold-back queue
process_hold_back_queue
()
# Process messages in the hold-back queue
process_hold_back_queue
()
# Process messages in the hold-back queue
except
socket
.
error
as
e
:
# Handle socket errors
except
socket
.
error
as
e
:
# Handle socket errors
print
(
f
"
An error occurred while listening:
{
e
}
"
)
print
(
f
"
An error occurred while listening:
{
e
}
"
)
break
break
except
KeyboardInterrupt
:
# Handle server shutdown via keyboard interrupt ????? Funktioniert das??
except
KeyboardInterrupt
:
# Handle server shutdown via keyboard interrupt ????? Funktioniert das??
print
(
"
\n
Shutting down server...
"
)
print
(
"
\n
Shutting down server...
"
)
break
break
...
@@ -384,7 +397,6 @@ def callback(new_value):
...
@@ -384,7 +397,6 @@ def callback(new_value):
########################### End - observation value changes leader ###########################
########################### End - observation value changes leader ###########################
########################### Heartbeat #################################
########################### Heartbeat #################################
def
heartbeat
():
def
heartbeat
():
...
@@ -437,7 +449,7 @@ if __name__ == "__main__":
...
@@ -437,7 +449,7 @@ if __name__ == "__main__":
thread2
=
threading
.
Thread
(
target
=
lausche_update_Ring
)
# Listens for ring updates
thread2
=
threading
.
Thread
(
target
=
lausche_update_Ring
)
# Listens for ring updates
#thread3 = threading.Thread(target=frage_benutzer) # Prompts the user for action --> Only for testing!
#thread3 = threading.Thread(target=frage_benutzer) # Prompts the user for action --> Only for testing!
thread4
=
threading
.
Thread
(
target
=
zuhören_election
)
# Listens for election messages
thread4
=
threading
.
Thread
(
target
=
zuhören_election
)
# Listens for election messages
last_three_messages
=
[
"
hallo
"
,
"
2
"
,
"
oma
"
]
last_three_messages
=
[]
thread5
=
threading
.
Thread
(
target
=
heartbeat
)
thread5
=
threading
.
Thread
(
target
=
heartbeat
)
# Start all threads
# Start all threads
thread1
.
start
()
thread1
.
start
()
...
...
This diff is collapsed.
Click to expand it.
2025-01-01_Client_V4.py
+
60
−
12
View file @
9b1822c2
#wenn zweiter client joint, wird kein verfügbarer server mehr angezeigt, das skript startet dreimal neu (?)
#dauerhafte ausgabe des waiting for response...
#funktion zum beenden des servers ergänzen (aka keyboardinterrupt)
#senden client info beim keyboardinterrupt
import
socket
import
socket
import
threading
import
threading
import
time
import
time
import
uuid
import
uuid
import
sys
import
sys
import
os
broadcast_ip
=
'
255.255.255.255
'
#change ip??? #hard coded?
broadcast_ip
=
'
255.255.255.255
'
#change ip??? #hard coded?
broadcast_port
=
55555
broadcast_port
=
55555
#client sends
broadcast_port2
=
33333
broadcast_port2
=
33333
#client listens
#local host information
#local host information
MY_HOST
=
socket
.
gethostname
()
MY_HOST
=
socket
.
gethostname
()
#socket.gethostbyname(socket.gethostname()) #getip
#socket.gethostbyname(socket.gethostname()) #getip
MY_IP
=
socket
.
gethostbyname
(
MY_HOST
)
MY_IP
=
socket
.
gethostbyname
(
MY_HOST
)
#print(f"host:{MY_HOST} and ip: {MY_IP}")
#print(f"host:{MY_HOST} and ip: {MY_IP}")
is_server_available
=
False
# create client-socket for broadcast
# create client-socket for broadcast
client_socket
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_DGRAM
)
client_socket
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_DGRAM
)
...
@@ -29,8 +37,11 @@ def listen_server():
...
@@ -29,8 +37,11 @@ def listen_server():
client_socket2
.
setsockopt
(
socket
.
SOL_SOCKET
,
socket
.
SO_REUSEADDR
,
1
)
client_socket2
.
setsockopt
(
socket
.
SOL_SOCKET
,
socket
.
SO_REUSEADDR
,
1
)
client_socket2
.
bind
((
''
,
broadcast_port2
))
# listen on broadcast #socket is bind to ALL available IP addresses
client_socket2
.
bind
((
''
,
broadcast_port2
))
# listen on broadcast #socket is bind to ALL available IP addresses
"""
receives messages from server.
"""
"""
receives messages from server.
"""
#client_socket2.settimeout(10) # timeout if server sends no acknowledgment
client_socket2
.
settimeout
(
10
)
global
message_id
global
message_id
global
is_server_available
last_response_time
=
time
.
time
()
#listener_ready.set() #makes sure that listener is ready
#listener_ready.set() #makes sure that listener is ready
while
True
:
while
True
:
try
:
try
:
...
@@ -43,19 +54,34 @@ def listen_server():
...
@@ -43,19 +54,34 @@ def listen_server():
#print(f"Received {data.decode()} from {address}") #debug
#print(f"Received {data.decode()} from {address}") #debug
#ignores broadcast messages with own ip #################please enable it after testing!!!!!!!!!!!!!!!!!!!S
#ignores broadcast messages with own ip #################please enable it after testing!!!!!!!!!!!!!!!!!!!S
#############NEED SMT TO IGNORE###############
#############NEED SMT TO IGNORE###############
#does not work?
#print("here id", message_id)
if
received_uuid
==
message_id
:
if
received_uuid
==
message_id
:
#print("ignore own msg")
#print("ignore own msg
s
")
continue
continue
else
:
else
:
_
,
_
,
client_message
=
text
.
partition
(
"
:
"
)
_
,
_
,
client_message
=
text
.
partition
(
"
:
"
)
print
(
client_message
.
strip
())
print
(
client_message
.
strip
())
if
decoded_message
.
__contains__
(
"
received
"
):
#and received_uuid==message_id:
print
(
"
server is active
"
,
decoded_message
)
is_server_available
=
True
#continue
else
:
raise
Exception
(
"
No active server detected
"
)
except
socket
.
timeout
:
#check if server is available
if
is_server_available
and
time
.
time
()
-
last_response_time
>
15
:
# 15 Sekunden ohne Antwort
print
(
"
Server is no longer available.
"
)
is_server_available
=
False
elif
not
is_server_available
:
print
(
"
No server available. Waiting for connection...
"
)
else
:
print
(
"
Waiting for server to respond...
"
)
#if decoded_message.split(":")[0]==already_received:
#except socket.timeout: #start script again if theres no answer from server
# continue
# print("No response from server. Restarting...")
#print("this decoded msg", decoded_message) #debug
# time.sleep(3)
# os.execv(sys.executable, ['python'] + sys.argv)
except
socket
.
error
as
e
:
except
socket
.
error
as
e
:
print
(
f
"
An error occurred while listening:
{
e
}
"
)
print
(
f
"
An error occurred while listening:
{
e
}
"
)
...
@@ -66,11 +92,27 @@ def sender():
...
@@ -66,11 +92,27 @@ def sender():
"""
Ermöglicht dem Benutzer, Nachrichten zu schreiben und zu senden.
"""
"""
Ermöglicht dem Benutzer, Nachrichten zu schreiben und zu senden.
"""
global
message_id
global
message_id
message_id
=
str
(
uuid
.
uuid4
())
message_id
=
str
(
uuid
.
uuid4
())
#ask for available server first
question
=
f
"
{
message_id
}
: server?
"
client_socket
.
sendto
(
question
.
encode
(),
(
broadcast_ip
,
broadcast_port
))
print
(
"
Connect to available server...
"
)
#data, address = client_socket.recvfrom(4096)
#server_answer = data.decode()
#if server_answer.__contains__("received"):
# print("Connected to server.")
nickname
=
input
(
"
Enter your nickname:
"
)
nickname
=
input
(
"
Enter your nickname:
"
)
just_nickname
=
f
"
{
nickname
}
entered the chat
"
.
encode
()
just_nickname
=
f
"
{
message_id
}
:
{
nickname
}
entered the chat
"
.
encode
()
#client_socket.sendto(just_nickname, (broadcast_ip, broadcast_port))
#client_socket.sendto(just_nickname, (broadcast_ip, broadcast_port))
client_socket
.
sendto
(
just_nickname
,
(
broadcast_ip
,
broadcast_port
))
client_socket
.
sendto
(
just_nickname
,
(
broadcast_ip
,
broadcast_port
))
#print("is it leader adresse here", leader_address)
#print("is it leader adresse here", leader_address)
#else:
#print("No server available")
#client_socket.close()
#os._exit(0)
try
:
try
:
while
True
:
while
True
:
...
@@ -84,7 +126,7 @@ def sender():
...
@@ -84,7 +126,7 @@ def sender():
client_socket
.
sendto
(
full_message
,
(
broadcast_ip
,
broadcast_port
))
client_socket
.
sendto
(
full_message
,
(
broadcast_ip
,
broadcast_port
))
#print("message sended to", broadcast_port)
#print("message sended to", broadcast_port)
except
KeyboardInterrupt
:
except
KeyboardInterrupt
:
######################whelp.......................
# Handle when the user presses Ctrl+C
# Handle when the user presses Ctrl+C
print
(
f
"
\n
{
nickname
}
left the chat.
"
)
print
(
f
"
\n
{
nickname
}
left the chat.
"
)
...
@@ -107,4 +149,10 @@ if __name__ == "__main__":
...
@@ -107,4 +149,10 @@ if __name__ == "__main__":
#listener_ready.wait()
#listener_ready.wait()
sender_thread
=
threading
.
Thread
(
target
=
sender
)
sender_thread
=
threading
.
Thread
(
target
=
sender
)
sender_thread
.
start
()
sender_thread
.
start
()
\ No newline at end of file
#####wenn kein server dann client beenden####
####sendungsbestätigung vom server, wenn client keine rückantwort erhält, dann keine server erreichbar####
####beim server rückantwort einbauen####
####when no answer then skip####
\ No newline at end of file
This diff is collapsed.
Click to expand it.
nickname.py
0 → 100644
+
28
−
0
View file @
9b1822c2
####client####:
if
decoded_message
.
__contains__
(
"
Choose an uniquely nickname
"
):
sender
()
#if decoded_message.split(":")[0]==already_received:
# continue
#print("this decoded msg", decoded_message) #debug
####server####
double_nickname
=
decoded_message
.
split
(
"
:
"
)[
1
]
# Extract nickname + entered the chat for checking whether a nickname is already taken
#print("!!!!!!!!!!nickname!!!", double_nickname)
current_nickname
=
double_nickname
.
split
(
"
entered the chat
"
)[
0
]
nicknames_in_chat
=
[
msg
.
split
(
"
:
"
)[
1
].
split
(
"
entered the chat
"
)[
0
]
for
msg
in
last_three_messages
if
"
entered the chat
"
in
msg
]
print
(
nicknames_in_chat
)
#uuid: susi
print
(
current_nickname
)
#susi
if
current_nickname
in
nicknames_in_chat
:
print
(
"
!!!!!!!!!!!!!!
"
,
current_nickname
)
broadcast
(
f
"
The nickname
{
current_nickname
}
is already taken. Choose an uniquely nickname
"
)
nicknames_in_chat
.
pop
()
last_three_messages
.
pop
()
continue
#if client has left
#make nickname available again
###################only proceed last 3-5 messages? if yes, how to check for nickname????
\ No newline at end of file
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment