-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonClient.py
More file actions
98 lines (81 loc) · 3.19 KB
/
PythonClient.py
File metadata and controls
98 lines (81 loc) · 3.19 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
import socket
import json
import time
class UnityClient:
"""
A simple TCP client to communicate with a Unity application.
This client sends JSON messages to a Unity server (e.g., for updating object positions).
"""
def __init__(self, host='127.0.0.1', port=25001):
"""
Initializes the client and connects to the Unity server.
:param host: IP address of the Unity server (default is localhost)
:param port: Port number Unity server is listening on (default is 25001)
"""
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect()
def connect(self):
"""
Establish a TCP connection to the Unity server.
"""
self.sock.connect((self.host, self.port))
print(f"[UnityClient] Connected to {self.host}:{self.port}")
def send_message(self, message: dict) -> dict:
"""
Send a JSON-formatted message to Unity and wait for a JSON response.
:param message: Dictionary to be serialized and sent
:return: Dictionary parsed from the server's response (empty if failed)
"""
msg_str = json.dumps(message)
self.sock.sendall(msg_str.encode('utf-8'))
response = self.sock.recv(4096).decode('utf-8') # Read up to 4KB of response
try:
return json.loads(response)
except json.JSONDecodeError:
print("[UnityClient] Failed to decode response.")
return {}
def close(self):
"""
Close the TCP connection to the Unity server.
"""
self.sock.close()
print("[UnityClient] Connection closed.")
if __name__ == "__main__":
client = UnityClient() # Start connection with Unity
try:
x = 0.0 # Position along x-axis (used to simulate movement)
direction = 0.1 # Movement increment per update
y = 0.0 # Constant y position
while True:
# Send position for Cube_01 (moving in x and z)
position_data_1 = {
"type": "position",
"id": "Cube_01",
"data": [x, y, -x] # Example: z is mirrored from x
}
response1 = client.send_message(position_data_1)
print("[PythonClient] Response for Cube_01:", response1)
# Send position for Cube_02 (moves in mirrored x, offset y, and x as z)
position_data_2 = {
"type": "position",
"id": "Cube_02",
"data": [-x, y + 0.5, x]
}
response2 = client.send_message(position_data_2)
print("[PythonClient] Response for Cube_02:", response2)
# Update x for oscillating motion between -1 and 1
x += direction
if x > 1.0:
x = 1.0
direction = -direction
elif x < -1.0:
x = -1.0
direction = -direction
time.sleep(0.1) # Send updates every 100 milliseconds
except KeyboardInterrupt:
print("Stopped by user")
finally:
# Ensure socket is properly closed
client.close()