-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
64 lines (53 loc) · 1.96 KB
/
client.py
File metadata and controls
64 lines (53 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from timeit import default_timer as timer
from dateutil import parser
import threading
import datetime
import socket
import time
# Client thread function used to send time at the client side
def startSendingTime(slave_client):
while True:
try:
# Provide server with clock time at the client
slave_client.send(str(datetime.datetime.now()).encode())
print("Recent time sent successfully")
time.sleep(5)
except Exception as e:
print(f"Error sending time to server: {e}")
break
# Client thread function used to receive synchronized time
def startReceivingTime(slave_client):
while True:
try:
# Receive data from the server
synchronized_time = parser.parse(slave_client.recv(1024).decode())
print("Synchronized time at the client is:", synchronized_time)
except Exception as e:
print(f"Error receiving synchronized time: {e}")
break
# Function used to synchronize client process time
def initiateSlaveClient(port=8080):
slave_client = socket.socket()
try:
# Connect to the clock server on local computer
slave_client.connect(('127.0.0.1', port))
print("Connected to the clock server.")
# Start sending time to the server
print("Starting to send time to the server...\n")
send_time_thread = threading.Thread(
target=startSendingTime,
args=(slave_client,)
)
send_time_thread.start()
# Start receiving synchronized time from server
print("Starting to receive synchronized time from server...\n")
receive_time_thread = threading.Thread(
target=startReceivingTime,
args=(slave_client,)
)
receive_time_thread.start()
except Exception as e:
print(f"Connection failed: {e}")
slave_client.close()
if __name__ == '__main__':
initiateSlaveClient(port=8080)