From 30f29f678b7178cad9c9fc1751c3eaf75ec87bb9 Mon Sep 17 00:00:00 2001 From: wenchun Date: Fri, 28 Mar 2025 11:24:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B8=AC=E8=A9=A6=E6=8E=A5=E6=94=B6=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/unitdev03/0328/testserver.py | 55 ++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/unitdev03/0328/testserver.py diff --git a/src/unitdev03/0328/testserver.py b/src/unitdev03/0328/testserver.py new file mode 100644 index 0000000..cce1478 --- /dev/null +++ b/src/unitdev03/0328/testserver.py @@ -0,0 +1,55 @@ +import socket +import re + +def start_udp_server(host='0.0.0.0', port=5000, buffer_size=1024): + server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + server_socket.bind((host, port)) + + print(f"UDP Server running on {host}:{port}") + print("Waiting for data...") + + position = None + velocity = None + + try: + while True: + data, client_address = server_socket.recvfrom(buffer_size) + + print(f"\n----- 接收到的資料 -----") + print(f"從 {client_address} 接收:") + + try: + decoded_data = data.decode('utf-8') + print(f"文本數據: {decoded_data}") + + # 直接使用正則表達式提取數據 + pos_match = re.search(r'"position":\[([-\d\.\,]+)\]', decoded_data) + vel_match = re.search(r'"velocity":\[([-\d\.\,]+)\]', decoded_data) + + if pos_match: + position_str = pos_match.group(1) + position = [float(x) for x in position_str.split(',')] + print(f"Position: {position}") + + if vel_match: + velocity_str = vel_match.group(1) + velocity = [float(x) for x in velocity_str.split(',')] + print(f"Velocity: {velocity}") + + # 這裡可以對 position 和 velocity 進行進一步操作 + + except UnicodeDecodeError: + print(f"二進制數據: {data.hex()}") + except Exception as e: + print(f"處理數據時出錯: {e}") + + print(f"數據大小: {len(data)} 字節") + print("-----------------------") + + except KeyboardInterrupt: + print("Server shutting down...") + finally: + server_socket.close() + +if __name__ == "__main__": + start_udp_server(port=5000) \ No newline at end of file