-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUDP_Pinger_Server_Heartbeat.py
75 lines (54 loc) · 2.13 KB
/
UDP_Pinger_Server_Heartbeat.py
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
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This server assumes that packet numbering starts at 1 and increases in increments of 1.
If the last N packets sent by a client are dropped, the server will not report lost packets
as the number of sent packets is not agreed upon beforehand.
"""
import random
from socket import *
import datetime
# Holds the sequence number and timestamp received in a UDP message
class UDPMessage:
def __init__(self, message):
"""Initializes the UDPMessage class"""
message = message.decode().split()
self.seqNum = int(message[0])
self.timestamp = datetime.datetime.strptime(message[1], '%H:%M:%S.%f')
# Initialize constants
HEARTBEAT_TIMEOUT = 3.0
TIME_DIFF = 1.0
UDP_IP = ''
UDP_PORT = 12000
BUFF_SIZE = 1024
MAX_NUM_UNRESPONSIVE_CLIENTS = 1
# Create a UDP socket
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Set a timeout for the socket in seconds
serverSocket.settimeout(HEARTBEAT_TIMEOUT)
# Assign IP address and port number to socket
serverSocket.bind((UDP_IP, UDP_PORT))
# Create a variable to store the previous message received
prevMessage = UDPMessage(('0 ' + str(datetime.datetime.now().time())).encode())
num_unresponsive_clients = 0
while True:
# Attempt to receive the client packet along with the address it is coming from
try:
message, address = serverSocket.recvfrom(BUFF_SIZE)
newMessage = UDPMessage(message)
# The client is alive
print('Received packet ' + str(newMessage.seqNum))
# Calculate the time diff
diff = (newMessage.timestamp - prevMessage.timestamp).total_seconds()
# Check for dropped packets
if newMessage.seqNum - prevMessage.seqNum > 1:
print('Dropped packet(s): ' + str(list(range(prevMessage.seqNum + 1, newMessage.seqNum)))[1:-1])
# Print the time diff
print('Time diff: ' + str(diff) + '\n')
prevMessage = newMessage
except:
# The client is dead
print('Unresponsive client\n')
num_unresponsive_clients += 1
if num_unresponsive_clients >= MAX_NUM_UNRESPONSIVE_CLIENTS:
break