-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
97 lines (74 loc) · 2.88 KB
/
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
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
# Author Forest Vey
import socket, sys
port = int(sys.argv[1])
# Create the socket object using DGRAM
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
loop = True
s.bind( ("", port) )
def twoBitUnpackerFirst(x):
return ((x & 240) >> 4)
def twoBitUnpackerSecond(x):
return (x & 15)
# Servers stay open for client acceptance
while loop == True:
# wait for a client to send a packet
packet, addr = s.recvfrom(1024)
operator = packet[0]
numVals = packet[1]
operand = 2
result = 0
# if bit 0 - add operands
if operator & 1 == 1:
for x in range(0,int((numVals + 1) / 2)):
if x == int((numVals + 1)/2 - 1) and numVals % 2 != 0:
result += int(twoBitUnpackerFirst(packet[operand]))
operand += 1
else:
result += int((twoBitUnpackerFirst(packet[operand])) + int(twoBitUnpackerSecond(packet[operand])))
operand += 1
packet = bytearray(4)
packet[0] = (result >> 24) & 255
packet[1] = (result >> 16) & 255
packet[2] = (result >> 8) & 255
packet[3] = result & 255
s.sendto(packet, addr)
# if bit 1 - minus operands
elif operator & 2 == 2:
result = int(twoBitUnpackerFirst(packet[operand]))
if len(packet) > 2:
result -= int(twoBitUnpackerSecond(packet[operand]))
operand += 1
for x in range(0,int((numVals - 1) / 2)):
if x == int((numVals - 1)/2 - 1) and numVals % 2 != 0:
result -= int(twoBitUnpackerFirst(packet[operand]))
else:
result -= int(twoBitUnpackerFirst(packet[operand]))
result -= int(twoBitUnpackerSecond(packet[operand]))
operand += 1
# if result is negative, sign the integer before placing in array
if result < 0:
result = result * -1
result = result | 2**31
packet = bytearray(4)
packet[0] = (result >> 24) & 255
packet[1] = (result >> 16) & 255
packet[2] = (result >> 8) & 255
packet[3] = result & 255
s.sendto(packet, addr)
# if bit 2 - multiply operands
elif operator & 4 == 4:
result = 1
for x in range(0,int((numVals + 1) / 2)):
if x == int((numVals + 1)/2 - 1) and numVals % 2 != 0:
result *= int(twoBitUnpackerFirst(packet[operand]))
operand += 1
else:
result *= int((twoBitUnpackerFirst(packet[operand])))
result *= int((twoBitUnpackerSecond(packet[operand])))
operand += 1
packet = bytearray(4)
packet[0] = (result >> 24) & 255
packet[1] = (result >> 16) & 255
packet[2] = (result >> 8) & 255
packet[3] = result & 255
s.sendto(packet, addr)