#include <MsgBoxConstants.au3>

Global $sIPAddress = "127.0.0.1"
Global $iPort = 9000
    
UDPStartup() ; Start the UDP service.
OnAutoItExitRegister("OnAutoItExit")



Func DPW_UDP_Server()
    ; Assign a Local variable the socket and bind to the IP Address and Port specified.
    Local $iSocket = UDPBind($sIPAddress, $iPort)

    ; If an error occurred display the error code and return False.
    If @error Then
        ; Someone is probably already binded on this IP Address and Port (script already running?).
        Local $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not bind, Error code: " & $iError)
        Return False
    EndIf

    ; Assign a Local variable to store the data received.
    Local $sReceived = ""

    Do
        ; We are waiting for the string "toto" OR "tata" (example script UDPSend): 4 bytes length.
        $sReceived = UDPRecv($iSocket, 4)
    Until $sReceived <> ""

    ; Notes: If you don't know how much length will be the data,
    ; use e.g: 2048 for maxlen parameter and call the function until the it returns nothing/error.

    ; Display the string received.
    MsgBox($MB_SYSTEMMODAL, "", "Server:" & @CRLF & "Received: " & $sReceived)

    ; Close the socket.
    UDPCloseSocket($iSocket)
EndFunc   ;==>MyUDP_Server

Func DPW_UDP_Send($var, $data)
    ; Assign a Local variable the socket and connect to a listening socket with the IP Address and Port specified.
    Local $iSocket = UDPOpen($sIPAddress, $iPort)
    Local $iError = 0

    ; If an error occurred display the error code and return False.
    If @error Then
        ; The server is probably offline/port is not opened on the server.
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not connect, Error code: " & $iError)
        Return False
    EndIf

    ; Send the string "toto" converted to binary to the server.
    ;UDPSend($iSocket, StringToBinary("toto"))
    $tran_id = 0
    $trans_pkt_id = 0
    $retry = 0
    $proto = "DPW_TRANS_VARVAL"
    UDPSend($iSocket, @UserName  & @LF &  $tran_id & @LF & $trans_pkt_id & @LF & $retry & @LF & $proto & @LF & $var & @LF & $data)
    
    $trans_pkt_id = 1
    $proto = "DPW_TRANS_CMD"
    UDPSend($iSocket, @UserName  & @LF &  $tran_id & @LF & $trans_pkt_id & @LF & $retry & @LF & $proto & @LF & "FLUSH_ALL_VARS")

    ; If an error occurred display the error code and return False.
    If @error Then
        $iError = @error
        MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Client:" & @CRLF & "Could not send the data, Error code: " & $iError)
        Return False
    EndIf

    ; Close the socket.
    UDPCloseSocket($iSocket)
EndFunc   ;==>MyUDP_Client

Func OnAutoItExit()
    UDPShutdown() ; Close the UDP service.
EndFunc   ;==>OnAutoItExit