Created
December 26, 2024 05:16
-
-
Save edxmorgan/98152e3625819659f89dd6741e0820a8 to your computer and use it in GitHub Desktop.
a simple dvl-a50 tcp python client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import json | |
def receive_json_data(host='192.168.2.95', port=16171): | |
""" | |
Connects to a TCP server and receives JSON data. | |
Args: | |
host (str): The server's hostname or IP address. | |
port (int): The port number to connect to. | |
Returns: | |
None | |
""" | |
try: | |
# Create a TCP/IP socket | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | |
print(f"Connecting to {host}:{port}...") | |
sock.connect((host, port)) | |
print("Connected successfully.") | |
buffer = "" | |
while True: | |
# Receive data in chunks | |
data = sock.recv(4096) | |
if not data: | |
# No more data from the server | |
print("No more data received. Closing connection.") | |
break | |
# Decode bytes to string and add to buffer | |
buffer += data.decode('utf-8') | |
# Process each complete JSON object in the buffer | |
while '\n' in buffer: | |
line, buffer = buffer.split('\n', 1) | |
if line.strip(): # Ignore empty lines | |
try: | |
json_data = json.loads(line) | |
handle_json(json_data) | |
except json.JSONDecodeError as e: | |
print(f"Failed to decode JSON: {e}") | |
print(f"Received line: {line}") | |
except ConnectionRefusedError: | |
print(f"Could not connect to {host}:{port}. Is the server running?") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
def handle_json(data): | |
""" | |
Processes the received JSON data. | |
Args: | |
data (dict): The JSON data as a dictionary. | |
Returns: | |
None | |
""" | |
# Example processing: print the JSON data | |
print("Received JSON data:") | |
print(json.dumps(data, indent=4)) | |
if __name__ == "__main__": | |
receive_json_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment