' Simple chat protocol over TCP with message framing
#COMPILE EXE
#DIM ALL

%MSG_HELLO = 1
%MSG_DATA = 2
%MSG_PING = 3
%MSG_PONG = 4
%MSG_GOODBYE = 5

FUNCTION TypeName(BYVAL t AS LONG) AS STRING
    IF t = %MSG_HELLO THEN FUNCTION = "HELLO"
    IF t = %MSG_DATA THEN FUNCTION = "DATA"
    IF t = %MSG_PING THEN FUNCTION = "PING"
    IF t = %MSG_PONG THEN FUNCTION = "PONG"
    IF t = %MSG_GOODBYE THEN FUNCTION = "GOODBYE"
    FUNCTION = "UNKNOWN"
END FUNCTION

FUNCTION BuildFrame(BYVAL msgType AS LONG, BYVAL payload AS STRING) AS LONG
    LOCAL plen AS LONG
    plen = LEN(payload)
    PRINT "Frame: type="; TypeName(msgType); " payload='"; payload; "'"
    PRINT "  Header(8): type="; msgType; " len="; plen
    PRINT "  Total: "; 8 + plen; " bytes"
    FUNCTION = msgType
END FUNCTION

SUB ChatClientSim()
    PRINT "Chat client:"
    BuildFrame(%MSG_HELLO, "user1")
    BuildFrame(%MSG_DATA, "Hello, world!")
    BuildFrame(%MSG_PING, "")
    BuildFrame(%MSG_GOODBYE, "bye")
END SUB

SUB ChatServerSim()
    PRINT ""
    PRINT "Chat server received frames:"
    LOCAL i AS LONG
    DIM types(0:3) AS LONG
    DIM payloads(0:3) AS STRING
    types(0) = %MSG_HELLO: payloads(0) = "user2"
    types(1) = %MSG_DATA: payloads(1) = "Hi from user2!"
    types(2) = %MSG_PING: payloads(2) = ""
    types(3) = %MSG_DATA: payloads(3) = "Are you there?"
    FOR i = 0 TO 3
        PRINT "  Received: "; TypeName(types(i)); "('"; payloads(i); "')"
    NEXT i
END SUB

SUB ProtocolExchange()
    PRINT ""
    PRINT "Full protocol exchange:"
    PRINT "  Client -> Server: HELLO('alice')"
    PRINT "  Server -> Client: HELLO('server1')"
    PRINT "  Client -> Server: DATA('Hello!')"
    PRINT "  Server -> Client: DATA('Hi alice!')"
    PRINT "  Client -> Server: PING"
    PRINT "  Server -> Client: PONG"
    PRINT "  Client -> Server: GOODBYE('bye')"
    PRINT "  Server -> Client: GOODBYE('bye')"
END SUB

SUB MessageBufferDemo()
    PRINT ""
    PRINT "Message buffering (multiple frames in one buffer):"
    DIM msgs(0:2) AS STRING
    msgs(0) = "msg1"
    msgs(1) = "msg2"
    msgs(2) = "msg3"
    LOCAL total AS LONG
    total = 0
    LOCAL i AS LONG
    FOR i = 0 TO 2
        LOCAL frameLen AS LONG
        frameLen = 8 + LEN(msgs(i))
        total = total + frameLen
        PRINT "  Frame "; i; ": "; frameLen; " bytes (cumulative "; total; ")"
    NEXT i
    PRINT "Total buffer: "; total; " bytes, "; i; " messages"
END SUB

FUNCTION PBMAIN() AS LONG
    PRINT "=== Chat Protocol Demo ==="
    PRINT "TCP message framing protocol"
    ChatClientSim()
    ChatServerSim()
    ProtocolExchange()
    MessageBufferDemo()
    PRINT "=== End Chat Protocol ==="
    FUNCTION = 0
END FUNCTION
