-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_server.py
70 lines (54 loc) · 2.12 KB
/
rpc_server.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
import sys
import signal
import socket
NUM_TRANSMISSIONS = 10
if len(sys.argv) < 2:
print("Usage: python3 " + sys.argv[0] + " server_port")
sys.exit(1)
assert len(sys.argv) == 2
server_port = int(sys.argv[1])
# TODO: Create a socket for the server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Setup signal handler to exit gracefully
def cleanup(sig, frame):
# TODO Close server's socket
server_socket.close()
sys.exit(0)
# SIGINT is sent when you press ctrl + C, SIGTERM if you use 'kill' or leave the shell
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
# TODO: Bind it to server_port
server_socket.bind(('', server_port))
# After binding the socket, print the server's IP Address and port
hostname = socket.gethostname()
server_ip = socket.gethostbyname(hostname)
print(f"Server is running on IP: {server_ip}, Port: {server_port}")
def is_prime(n):
"""Function to check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print("start while loop")
while True:
print("in while loop")
# TODO: Receive RPC request from client
rpc_data, client_address = server_socket.recvfrom(1024)
print("message receive")
print(f"Received data: {rpc_data}")
print(f"Received client_address: {client_address}")
# TODO: Turn byte array that you received from client into a string variable called rpc_data
rpc_data = rpc_data.decode()
# TODO: Parse rpc_data to get the argument to the RPC.
# Remember that the RPC request string is of the form prime(NUMBER)
num = int(rpc_data.split('(')[1].split(')')[0])
# TODO: Print out the argument for debugging
print(f"Received number: {num}")
# TODO: Compute if the number is prime (return a 'yes' or a 'no' string)
response = 'yes' if is_prime(num) else 'no'
# TODO: Send the result of primality check back to the client who sent the RPC request
server_socket.sendto(response.encode(), client_address)
# TODO: Close server's socket
# it closes it selve with the cleanup function