Skip to content

Commit decd68c

Browse files
committed
Added new test to read received data through a socket
1 parent 185c229 commit decd68c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import socket
2+
import sys
3+
import struct
4+
5+
# The following methods are used to simulate a moving shape (not used in this version)
6+
def initialize_position():
7+
x = random.randint(lower_bound, upper_bound_x)
8+
y = random.randint(lower_bound, upper_bound_y)
9+
direction_x = random.choice([-1, 1])
10+
direction_y = random.choice([-1, 1])
11+
return x, y, direction_x, direction_y
12+
13+
14+
def move_position(x, y, direction_x, direction_y):
15+
x += direction_x * step_size
16+
y += direction_y * step_size
17+
18+
if x <= lower_bound or x >= upper_bound_x:
19+
direction_x = -direction_x
20+
x = max(lower_bound, min(x, upper_bound_x))
21+
22+
if y <= lower_bound or y >= upper_bound_y:
23+
direction_y = -direction_y
24+
y = max(lower_bound, min(y, upper_bound_y))
25+
26+
return x, y, direction_x, direction_y
27+
28+
29+
# Receive and parse data from the socket
30+
def receive_data(sock):
31+
# Receive data from the socket
32+
data, addr = sock.recvfrom(1024) # Buffer size of 1024 bytes
33+
# Unpack the data as 3 int types (x, y, shapesize)
34+
x, y, size = struct.unpack("iii", data)
35+
return x, y, size, addr
36+
37+
38+
def main():
39+
if len(sys.argv) != 2:
40+
print(
41+
"Usage: python3 read_shape_from_socket.py <port>"
42+
)
43+
return
44+
45+
# Input arguments
46+
port = int(sys.argv[1])
47+
48+
samples_received = 0
49+
50+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
51+
try:
52+
# Bind the socket to listen on the specified port
53+
sock.bind(('', port))
54+
print(f"Listening for shape data on port {port}...")
55+
56+
while True:
57+
# Receive data from the socket
58+
x, y, size, addr = receive_data(sock)
59+
60+
# Print the received shape data
61+
samples_received += 1
62+
print(f"Sample #{samples_received} from {addr}: x={x}, y={y}, size={size}")
63+
64+
except KeyboardInterrupt:
65+
print("\nExiting...")
66+
except Exception as e:
67+
print(f"Error: {e}")
68+
69+
70+
if __name__ == "__main__":
71+
main()

0 commit comments

Comments
 (0)