-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
209 lines (175 loc) · 8.48 KB
/
server.py
File metadata and controls
209 lines (175 loc) · 8.48 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import numbers
import api
import argparse
import socket
import threading
CACHE_POLICY = True # whether to cache responses or not
# the maximum time that the response can be cached for (in seconds)
CACHE_CONTROL = 2 ** 16 - 1
def calculate(expression: api.Expr, steps: list[str] = []) -> tuple[numbers.Real, list[api.Expression]]:
'''
Function which calculates the result of an expression and returns the result and the steps taken to calculate it.
The function recursively descends into the expression tree and calculates the result of the expression.
Each expression wraps the result of its subexpressions in parentheses and adds the result to the steps list.
'''
expr = api.type_fallback(expression)
const = None
if isinstance(expr, api.Constant) or isinstance(expr, api.NamedConstant):
const = expr
elif isinstance(expr, api.BinaryExpr):
left_steps, right_steps = [], []
left, left_steps = calculate(expr.left_operand, left_steps)
for step in left_steps[:-1]:
steps.append(api.BinaryExpr(
step, expr.operator, expr.right_operand))
right, left_steps = calculate(expr.right_operand, right_steps)
for step in right_steps[:-1]:
steps.append(api.BinaryExpr(left, expr.operator, step))
steps.append(api.BinaryExpr(left, expr.operator, right))
const = api.Constant(expr.operator.function(left, right))
steps.append(const)
elif isinstance(expr, api.UnaryExpr):
operand_steps = []
operand, operand_steps = calculate(expr.operand, operand_steps)
for step in operand_steps[:-1]:
steps.append(api.UnaryExpr(expr.operator, step))
steps.append(api.UnaryExpr(expr.operator, operand))
const = api.Constant(expr.operator.function(operand))
steps.append(const)
elif isinstance(expr, api.FunctionCallExpr):
args = []
for arg in expr.args:
arg_steps = []
arg, arg_steps = calculate(arg, arg_steps)
for step in arg_steps[:-1]:
steps.append(api.FunctionCallExpr(expr.function, *
(args + [step] + expr.args[len(args) + 1:])))
args.append(arg)
steps.append(api.FunctionCallExpr(expr.function, *args))
const = api.Constant(expr.function.function(*args))
steps.append(const)
else:
raise TypeError(f"Unknown expression type: {type(expr)}")
return const.value, steps
def process_request(request: api.CalculatorHeader) -> api.CalculatorHeader:
'''
Function which processes a CalculatorRequest and builds a CalculatorResponse.
'''
result, steps = None, []
try:
if request.is_request:
expr = api.data_to_expression(request)
result, steps = calculate(expr, steps)
else:
raise TypeError("Received a response instead of a request")
except Exception as e:
return api.CalculatorHeader.from_error(e, api.CalculatorHeader.STATUS_CLIENT_ERROR, CACHE_POLICY, CACHE_CONTROL)
if request.show_steps:
steps = [api.stringify(step, add_brackets=True) for step in steps]
else:
steps = []
return api.CalculatorHeader.from_result(result, steps, CACHE_POLICY, CACHE_CONTROL)
def server(host: str, port: int) -> None:
# socket(socket.AF_INET, socket.SOCK_STREAM)
# (1) AF_INET is the address family for IPv4 (Address Family)
# (2) SOCK_STREAM is the socket type for TCP (Socket Type) - [SOCK_DGRAM is the socket type for UDP]
# Note: context manager ('with' keyword) closes the socket when the block is exited
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
# SO_REUSEADDR is a socket option that allows the socket to be bound to an address that is already in use.
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Prepare the server socket
# * Fill in start (1)
###add#### (1)
# The bind function determines the IP and port to which the socket will be bound,
# we received the data for the socket in the parameters passed to the function (host & port).
# The listen function causes the socket to listen and be ready to receive incoming connections.
# (we can define how many connections will wait in the queue inside the brackets).
server_socket.bind((host, port))
server_socket.listen()
###add#### (1)
# * Fill in end (1)
threads = []
print(f"Listening on {host}:{port}")
while True:
try:
# Establish connection with client.
# * Fill in start (2)
###add#### (2)
# When connecting to the server socket,
# the accept function returns the client's socket and its IP address and port.
client_socket, address = server_socket.accept()
###add#### (2)
# * Fill in end (2)
# Create a new thread to handle the client request
thread = threading.Thread(target=client_handler, args=(
client_socket, address))
thread.start()
threads.append(thread)
except KeyboardInterrupt:
print("Shutting down...")
break
for thread in threads: # Wait for all threads to finish
thread.join()
def client_handler(client_socket: socket.socket, client_address: tuple[str, int]) -> None:
'''
Function which handles client requests
'''
client_addr = f"{client_address[0]}:{client_address[1]}"
client_prefix = f"{{{client_addr}}}"
with client_socket: # closes the socket when the block is exited
print(f"Connection established with {client_addr}")
while True:
# * Fill in start (3)
###add#### (3)
# The recv function reads the data sent by the client from the socket and stores it in the data variable.
# In addition, we have determined that the size of the information that can be received
# from the client in each message is 65536 bytes.
# (As exported in the api file - BUFFER_SIZE = 65536)
data = client_socket.recv(api.BUFFER_SIZE)
###add#### (3)
# * Fill in end (3)
# * Change in start (1)
if not data:
break
# * Change in end (1)
try:
try:
request = api.CalculatorHeader.unpack(data)
except Exception as e:
raise api.CalculatorClientError(
f'Error while unpacking request: {e}') from e
print(f"{client_prefix} Got request of length {len(data)} bytes")
response = process_request(request)
response = response.pack()
print(
f"{client_prefix} Sending response of length {len(response)} bytes")
# * Fill in start (4)
###add#### (4)
# After the calculation is done,
# the sendall function sends the response to the client.
client_socket.sendall(response)
###add#### (4)
# * Fill in end (4)
except Exception as e:
print(f"Unexpected server error: {e}")
client_socket.sendall(api.CalculatorHeader.from_error(
e, api.CalculatorHeader.STATUS_SERVER_ERROR, CACHE_POLICY, CACHE_CONTROL).pack())
# * Change in start (2)
###add#### (5)
# After exiting the while True loop,
# we added a close command that closes the socket
client_socket.close()
###add#### (5)
# * Change in end (2)
print(f"{client_prefix} Connection closed")
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='A Calculator Server.')
arg_parser.add_argument('-p', '--port', type=int,
default=api.DEFAULT_SERVER_PORT, help='The port to listen on.')
arg_parser.add_argument('-H', '--host', type=str,
default=api.DEFAULT_SERVER_HOST, help='The host to listen on.')
args = arg_parser.parse_args()
host = args.host
port = args.port
server(host, port)