import socket import serial TCP_IP = "192.168.1.1" TCP_PORT = 8080 msg_size = 1024 message = bytes(i % 256 for i in range(msg_size)) dropped = True ser = serial.Serial('COM6', 921600, timeout=0.01) ser.reset_input_buffer() if ser.in_waiting: print("that doesn't work") while True: if dropped: attempts = 0 while attempts < 5: print("Trying to connect") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2) try: sock.connect((TCP_IP, TCP_PORT)) dropped = False break except: attempts += 1 if dropped: print("Failed to connect") break print("connected") try: print("Sending {} bytes".format(len(message))) ser.write(message) except Exception as e: print("Failed to send all data") continue received = [] while len(received) < msg_size: try: just_received = sock.recv(msg_size - len(received)) except Exception as e: print("Exception when receiving: ", e) break if len(just_received) == 0: print("Your socket broke") break received.extend(just_received) if len(received) != msg_size: print("\tError: Received {} bytes".format(len(received))) elif bytes(received) != message: print("\tError: Received data does not match") else: print("\tYou're a winner!") debug_msg = ser.read(4096) if len(debug_msg) != 0: print(debug_msg.decode())