import socket
import serial

TCP_IP = "192.168.1.1"
TCP_PORT = 8080

msg_size = 1024*100
message = bytes(i % 256 for i in range(msg_size))
dropped = True

ser = serial.Serial('COM6', 921600, timeout=5)
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)))
        sock.sendall(message)
    except Exception as e:
        print("Failed to send all data")
        continue
    received = ser.read(msg_size)
    if len(received) != msg_size:
        print("\tError: Received {} bytes".format(len(received)))
    elif received != message:
        print("\tError: Received data does not match")
    else:
        print("\tYou're a winner!")