# Function Reference

# TCPRecv

Receives data from a connected socket.

TCPRecv ( mainsocket, maxlen [, flag = 0] )

## Parameters

mainsocket | The connected socket identifier (SocketID) as returned by a TCPAccept() or a TCPConnect() function.
maxlen | max # of characters to receive.
flag | [optional] Forces the function to return binary data if set to 1 (default is 0, and will auto detect between binary/string). $TCP_DATA_DEFAULT (0) - (Default) will auto detect between binary/string $TCP_DATA_BINARY (1) - return binary data Constants are defined in "AutoItConstants.au3".

## Return Value

Success: | the binary/string sent by the connected socket. See remark.
Failure: | Empty string and sets the @error flag to non-zero.
@error: | -1 invalid socket. -2 not connected. Windows API WSAGetLastError return value (see MSDN).
@extended: | 1 no byte received.

## Remarks

For backwards compatibility reasons this function will try to return strings by default. If null (0x00) characters are received then the return value will be a binary type.
To force the function to always return binary data (the most sensible option) then use the "flag" parameter set to 1.
If Unicode strings need to be transmitted they must be encoded/decoded with StringToBinary()/BinaryToString().
When there is no more data to receive the return value is "" and @extended = 1.
A test of TCPSend() and TCPRecv() can be launch with the following button :
Open TCPSend-Recv[2].au3

## Related

BinaryLen, BinaryMid, BinaryToString, TCPAccept, TCPConnect, TCPSend, TCPStartup, TCPTimeout (Option)

## Example

### Example 1

    #include <GUIConstantsEx.au3>
    #include <MsgBoxConstants.au3>
    #include <WinAPIError.au3>

    ; Start First clicking on "1. Server"
    ; Then start a second instance of the script selecting "2. Client"

    Example()

    Func Example()
        TCPStartup() ; Start the TCP service.

        ; Register OnAutoItExit to be called when the script is closed.
        OnAutoItExitRegister("OnAutoItExit")

        ; Assign Local variables the loopback IP Address and the Port.
        Local $sIPAddress = "127.0.0.1" ; This IP Address only works for testing on your own computer.
        Local $iPort = 65432 ; Port used for the connection.

        #Region GUI
        Local $sTitle = "TCP Start"
        Local $hGUI = GUICreate($sTitle, 250, 70)

        Local $idBtn_Server = GUICtrlCreateButton("1. Server", 65, 10, 130, 22)

        Local $idBtn_Client = GUICtrlCreateButton("2. Client", 65, 40, 130, 22)

        GUISetState(@SW_SHOW, $hGUI)

        While 1
            Switch GUIGetMsg()
                Case $GUI_EVENT_CLOSE
                    ExitLoop
                Case $idBtn_Server
                    WinSetTitle($sTitle, "", "TCP Server started")
                    GUICtrlSetState($idBtn_Client, $GUI_HIDE)
                    GUICtrlSetState($idBtn_Server, $GUI_DISABLE)
                    If Not MyTCP_Server($sIPAddress, $iPort) Then ExitLoop
                Case $idBtn_Client
                    WinSetTitle($sTitle, "", "TCP Client started")
                    GUICtrlSetState($idBtn_Server, $GUI_HIDE)
                    GUICtrlSetState($idBtn_Client, $GUI_DISABLE)
                    If Not MyTCP_Client($sIPAddress, $iPort) Then ExitLoop
            EndSwitch

            Sleep(10)
        WEnd

        #EndRegion GUI
    EndFunc   ;==>Example

    Func MyTCP_Client($sIPAddress, $iPort)
        ; Assign a Local variable the socket and connect to a listening socket with the IP Address and Port specified.
        Local $iSocket = TCPConnect($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 & @CRLF & _WinAPI_GetErrorMessage($iError))
            Return False
        EndIf

        ; Send the string "tata" to the server.
        TCPSend($iSocket, "tata")

        ; 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 & @CRLF & _WinAPI_GetErrorMessage($iError))
            Return False
        EndIf

        ; Close the socket.
        TCPCloseSocket($iSocket)
    EndFunc   ;==>MyTCP_Client

    Func MyTCP_Server($sIPAddress, $iPort)
        Local $aPos = WinGetPos("TCP Server started")
        WinMove("TCP Server started", "", $aPos[0], $aPos[1] - 100)
        ; Assign a Local variable the socket and bind to the IP Address and Port specified with a maximum of 100 pending connections.
        Local $iListenSocket = TCPListen($sIPAddress, $iPort, 100)
        Local $iError = 0

        If @error Then
            ; Someone is probably already listening on this IP Address and Port (script already running?).
            $iError = @error
            MsgBox(BitOR($MB_SYSTEMMODAL, $MB_ICONHAND), "", "Server:" & @CRLF & "Could not listen, Error code: " & $iError & @CRLF & _WinAPI_GetErrorMessage($iError))
            Return False
        EndIf

        ; Assign a Local variable to be used by the Client socket.
        Local $iSocket = 0

        Do ; Wait for someone to connect (Unlimited).
            ; Accept incomming connections if present (Socket to close when finished; one socket per client).
            $iSocket = TCPAccept($iListenSocket)

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

            If GUIGetMsg() = $GUI_EVENT_CLOSE Then Return False
        Until $iSocket <> -1 ;if different from -1 a client is connected.

        ; Close the Listening socket to allow afterward binds.
        TCPCloseSocket($iListenSocket)

        ; Assign a Local variable the data received.
        Local $sReceived = TCPRecv($iSocket, 4) ;we're waiting for the string "tata" OR "toto" (example script TCPRecv): 4 bytes length.

        ; 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.
        TCPCloseSocket($iSocket)
    EndFunc   ;==>MyTCP_Server

    Func OnAutoItExit()
        TCPShutdown() ; Close the TCP service.
    EndFunc   ;==>OnAutoItExit

### Example 2

    ; I am the client, start me after the server! (Start first the example 2 of the TCPSend function).

    #include <AutoItConstants.au3>
    #include <FileConstants.au3>
    #include <MsgBoxConstants.au3>
    #include <WinAPIError.au3>

    Example()

    Func Example()
        Local $sMsgBoxTitle = "AutoItVersion = " & @AutoItVersion

        TCPStartup() ; Start the TCP service.

        ; Register OnAutoItExit to be called when the script is closed.
        OnAutoItExitRegister("OnAutoItExit")

        ; Assign Local variables the loopback IP Address and the Port.
        Local $sIPAddress = "127.0.0.1" ; This IP Address only works for testing on your own computer.
        Local $iPort = 65432 ; Port used for the connection.

        ; Assign a Local variable the socket and connect to a listening socket with the IP Address and Port specified.
        Local $iSocket = TCPConnect($sIPAddress, $iPort)

        ; 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.
            MsgBox(($MB_SYSTEMMODAL + $MB_ICONHAND), $sMsgBoxTitle, "Client: Could not connect" & @CRLF & " Error code: " & @error & @CRLF & @CRLF & _WinAPI_GetErrorMessage(@error))
            Return False
        EndIf

        ; Assign a Local variable the path of the file which will be received.
        Local $sFilePath = @TempDir & "\temp.dat"
        FileDelete($sFilePath)

        ; If an error occurred display the error code and return False.
        If @error Then
            MsgBox(($MB_SYSTEMMODAL + $MB_ICONEXCLAMATION), $sMsgBoxTitle, "Client: Invalid file chosen" & @CRLF & " Error code: " & @error & @CRLF & @CRLF & _WinAPI_GetErrorMessage(@error))
            Return False
        EndIf

        ; Assign a Local variable the handle of the file opened in binary overwrite mode.
        Local $hFile = FileOpen($sFilePath, BitOR($FO_BINARY, $FO_OVERWRITE))

        ; Assign Locales Constant variables the number representing 4 KiB; the binary code for the end of the file and the length of the binary code.
        Local $i4KiB = 4096
        If $CmdLine[0] Then $i4KiB = $CmdLine[1]

        Local $dData, $nReceivedBytes = 0, $n = 0, $fDiffTime, $hTimer = TimerInit()
        #forceref $dData
        While 1
            $dData = TCPRecv($iSocket, $i4KiB, $TCP_DATA_BINARY)

            ; If an error occurred display the error code and return False.
            If @error Then
                MsgBox(($MB_SYSTEMMODAL + $MB_ICONHAND), $sMsgBoxTitle, "Client: Connection lost n=" & $n & @CRLF & " Error code: " & @error & @CRLF & @CRLF & _WinAPI_GetErrorMessage(@error))
                Return False
            ElseIf @extended = 1 Or BinaryLen($dData) = 0 Then
                ; If nothing is received
                ExitLoop
            EndIf

            $nReceivedBytes += BinaryLen($dData)
            $n += 1
    ;~      FileWrite($hFile, $dData) ; to be uncommented if file content to be written
        WEnd
        $fDiffTime = TimerDiff($hTimer)
        ; Close the file handle.
        FileClose($hFile)

        ; Display the successful message.
    ;~  MsgBox($MB_SYSTEMMODAL, "", "Client:" & @CRLF & "File received nbBytes=" & & FileGetSize($sFilePath))
        MsgBox($MB_SYSTEMMODAL, $sMsgBoxTitle, "Client: receivedBytes = " & $nReceivedBytes & " packetSize = " & $i4KiB & @CRLF & "File received TCPRecv = " & Int($fDiffTime / $n * 1000) & "µs Total = " & Int($fDiffTime) & "ms nPacket = " & $n)

        ; Close the socket.
        TCPCloseSocket($iSocket)
    EndFunc   ;==>Example

    Func OnAutoItExit()
        TCPShutdown() ; Close the TCP service.
    EndFunc   ;==>OnAutoItExit