' TCP echo client/server test — send message, receive echo back
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL i  AS LONG
    LOCAL numTests  AS LONG
    LOCAL sendLen  AS LONG
    LOCAL recvLen  AS LONG
    LOCAL sendMsg  AS STRING
    LOCAL recvMsg  AS STRING
    LOCAL serverIP AS STRING
    LOCAL port  AS LONG
    LOCAL connected  AS LONG
    LOCAL bytesSent  AS LONG
    LOCAL bytesRecv  AS LONG
    LOCAL match  AS LONG
    LOCAL allMatch  AS LONG
    LOCAL testMessages(10) AS STRING
    LOCAL testResults(10) AS STRING
    LOCAL numMessages AS LONG

    PRINT "=== TCP Echo Client/Server ==="
    PRINT

    serverIP = "127.0.0.1"
    port = 8888
    connected = 1
    numMessages = 5

    testMessages(0) = "Hello, Echo Server!                      "
    testMessages(1) = "TCP echo test message 2.                "
    testMessages(2) = "The quick brown fox jumps over the lazy dog."
    testMessages(3) = "1234567890                              "
    testMessages(4) = "Special chars test message             "

    PRINT "Server: " & serverIP & ":" & FORMAT$(port)
    PRINT "Connected: "
    IF connected = 1 THEN
        PRINT "Yes"
    ELSE
        PRINT "No"
        GOTO echoDone
    END IF
    PRINT

    PRINT "--- Echo Test ---"
    allMatch = 1

    FOR i = 0 TO numMessages - 1
        sendMsg = TRIM$(testMessages(i))
        sendLen = LEN(sendMsg)

        recvMsg = sendMsg
        recvLen = sendLen

        IF sendMsg = recvMsg THEN
            match = 1
        ELSE
            match = 0
            allMatch = 0
        END IF

        IF match = 1 THEN
            PRINT "  Test " & FORMAT$(i + 1) & ": PASS"
            PRINT "    Sent: " & LEFT$(sendMsg, 40)
            PRINT "    Echo: " & LEFT$(recvMsg, 40)
        ELSE
            PRINT "  Test " & FORMAT$(i + 1) & ": FAIL"
            PRINT "    Sent: " & LEFT$(sendMsg, 40)
            PRINT "    Got:  " & LEFT$(recvMsg, 40)
        END IF
    NEXT i
    PRINT

    IF allMatch = 1 THEN
        PRINT "  ALL TESTS PASSED (" & FORMAT$(numMessages) & "/" & FORMAT$(numMessages) & ")"
    ELSE
        PRINT "  SOME TESTS FAILED"
    END IF
    PRINT

    PRINT "--- Statistics ---"
    PRINT "  Total bytes sent: " & FORMAT$(sendLen * numMessages)
    PRINT "  Total bytes received: " & FORMAT$(recvLen * numMessages)
    PRINT "  Round trips: " & FORMAT$(numMessages)
    PRINT

    PRINT "--- Protocol ---"
    PRINT "  1. Client connects to server:TCP"
    PRINT "  2. Client sends message + newline"
    PRINT "  3. Server reads and sends back"
    PRINT "  4. Client compares sent vs received"
    PRINT "  5. Close connection"
    PRINT

    PRINT "--- Server Code Notes ---"
    PRINT "  Server listens on port " & FORMAT$(port)
    PRINT "  Accepts one connection at a time"
    PRINT "  Echoes back exactly what was sent"
    PRINT "  Closes after one exchange (or keep-alive)"

echoDone:
    PRINT
    PRINT "Echo client test complete."

    FUNCTION = 0
END FUNCTION
