測試接收端
parent
8bc7bfee86
commit
30f29f678b
@ -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)
|
||||
Loading…
Reference in New Issue