Jump to content

TCP Send Message


Recommended Posts

Hi,

I created a TCP send & recieve function based on the example in the help file but, TCPConnect is not working on PC 01 nor TCPListen on PC 02.
Did I miss something?

Global $TestMessage = "test text"
Global $TestGateway = ""          ; -IPv4 Gateway IP goes here-
Global $TestPort = 65432


_LanMessenger(0, $TestGateway, $TestPort, $TestMessage)                                     ; Send Message // Used on PC01


MsgBox(0, "Recieved Message", "|" & _LanMessenger(1, $TestGateway, $TestPort) & "|")        ; Recieve Message // Used on PC02







Func _LanMessenger($Mode, $Gateway, $Port, $Message = "")
    Local $Socket, $ListenSocket, $Recieved
    TCPStartup()
    Switch $Mode
        Case 0                                              ; // TCP Client | Send Message
            $Socket = TCPConnect($Gateway, $Port)
            If @error Then
                MsgBox(16, "Error", "Could not connect!")
                Return False
            EndIf
            $Message = StringToBinary($Message, 4)          ; UTF-8 Binary
            TCPSend($Socket, $Message)
            If @error Then
                MsgBox(16, "Error", "Could not send the data!")
                Return False
            EndIf
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return True
        Case 1                                              ; // TCP Server | Recieve Message
            $ListenSocket = TCPListen($Gateway, $Port, 100)
            If @error Then
                MsgBox(16, "Error", "Could not listen!")
                Return False
            EndIf
            Do
                ; Wait for someone to connect (Unlimited).
                ; Accept incomming connecions if present (Socket to close when finished; one socket per client).
                $Socket = TCPAccept($ListenSocket)
                If @error Then
                    MsgBox(16, "Error", "Could not accept the incoming connection")
                    Return False
                EndIf
            Until $Socket <> -1  ;if different from -1 a client is connected.
            TCPCloseSocket($ListenSocket)
            $Recieved = TCPRecv($Socket, 2048, 1)           ; Return message as binary data
            $Recieved = BinaryToString($Recieved, 4)        ; Convert back to string
            TCPShutdown()
            Return $Recieved
    EndSwitch
EndFunc   ;==>_LanMessenger

 

Link to comment
Share on other sites

I have modified your script a little. I left notes to read.

Start the server first, then you can send.

Global $TestMessage = "test text"
Global $TestGateway = ""; -IPv4 Gateway IP goes here-
Global $TestPort = 65432

_LanMessenger(0, $TestGateway, $TestPort, $TestMessage); Send Message // Used on PC01

MsgBox(0, "Recieved Message", "|" & _LanMessenger(1, $TestGateway, $TestPort) & "|"); Recieve Message // Used on PC02

Func _LanMessenger($Mode, $Gateway, $Port, $Message = "")
    Opt('TCPTimeout', 10); <-- added so that response time will be efficient with newer versions of AutoIt
    TCPStartup()

    Local $Socket, $ListenSocket, $Received

    Switch $Mode
        Case 0; // TCP Client | Send Message
            $Socket = TCPConnect($Gateway, $Port)
            If @error Then
                MsgBox(16, "Error", "Could not connect!")
                Return False
            EndIf
            $Message = StringToBinary($Message, 4); UTF-8 Binary
            TCPSend($Socket, $Message)
            If @error Then
                MsgBox(16, "Error", "Could not send the data!")
                Return False
            EndIf
            Sleep(1000); <-- necessary, so that the socket doesn't disconnect too soon
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return True
        Case 1; // TCP Server | Recieve Message
            $ListenSocket = TCPListen($Gateway, $Port, 100)
            If @error Then
                MsgBox(16, "Error", "Could not listen!")
                Return False
            EndIf

            Do
                Sleep(10); <-- necessary, so that TCPAccept is not polled in micro-seconds
                ; Wait for someone to connect (Unlimited).
                ; Accept incomming connecions if present (Socket to close when finished; one socket per client).
                $Socket = TCPAccept($ListenSocket)
            Until $Socket > 0; if greater than 0 then a client is connected.

            For $i = 1 To 100; <-- may need to increase if response is too slow
                $Received = TCPRecv($Socket, 2048, 1); Return message as binary data
                If $Received <> '' Then
                    $Received = BinaryToString($Received, 4); Convert back to string
                    ExitLoop
                EndIf
                Sleep(10)
            Next

            TCPCloseSocket($ListenSocket)
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return $Received
    EndSwitch
EndFunc;==>_LanMessenger

 

"The mediocre teacher tells. The Good teacher explains. The superior teacher demonstrates. The great teacher inspires." -William Arthur Ward

Link to comment
Share on other sites

Thanks @ripdad !
I improved upon your code too and also included a broadcast client mode.

Opt('TCPTimeout', 10)   ; <-- added so that response time will be efficient with newer versions of AutoIt

Global $TestMessage = "lorem ipsum dolor sit amet"
Global $TestSendToIp = "" ; Ipv4 Network or Ip goes here



MsgBox(0, "Recieved Message", "|" & _LanMessenger(0) & "|")                                         ; TCP Server
;~ _LanMessenger(2, $TestSendToIp, $TestMessage)                                                       ; TCP Client (uncomment on client)





Func _LanMessenger($Mode, $SendToIp = "", $Message = "")
    Local Const $Port = 51421, $PendingConnections = 100                            ; TCP ONLY port
    Local $Socket, $ListenSocket, $Recieved, $Broadcast
    TCPStartup()
    Switch $Mode
        Case 0                                                                      ; // TCP Server | Start First | Recieve Message
            $ListenSocket = TCPListen(@IPAddress1, $Port, $PendingConnections)
            If @error Then
                Return SetError(@error)
            EndIf
            Do
                Sleep(10)                                                           ; <-- necessary, so that TCPAccept is not polled in micro-seconds
                $Socket = TCPAccept($ListenSocket)
            Until $Socket > 0                                                       ; if greater than 0 then a client is connected.
            For $i = 1 To 100                                                       ; <-- may need to increase if response is too slow
                $Received = TCPRecv($Socket, 2048, 1)                               ; Return message as binary data
                If $Received Then
                    $Received = BinaryToString($Received, 4)                        ; Convert back to string
                    ExitLoop
                EndIf
                Sleep(10)
            Next
            TCPCloseSocket($ListenSocket)
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return $Received
        Case 1                                                                      ; // TCP Client | Start After | Send Message
            If Not $SendToIp Then
                Return SetError(1)
            EndIf
            $Socket = TCPConnect($SendToIp, $Port)
            If @error Then
                Return SetError(@error)
            EndIf
            $Message = StringToBinary($Message, 4)                                  ; UTF-8 Binary
            TCPSend($Socket, $Message)
            If @error Then
                Return SetError(@error)
            EndIf
            Sleep(2000)                                                             ; <-- necessary, so that the socket doesn't disconnect too soon
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return True
        Case 2                                                                      ; // TCP Broadcast Client | Start After | Send Message
            If Not $SendToIp Then
                Return SetError(1)
            EndIf
            For $x = 0 To 254 Step 1                                                ; a valid host cannot be larger than 254
                Sleep(10)
                $Broadcast = $SendToIp & $x                                         ; <-- Network & Host ex: 'xxx.xxx.xxx.' & 'x'
                $Socket = TCPConnect($Broadcast, $Port)
                If @error Then
                    ContinueLoop                                                    ; If error then don't bother... try another Ip
                Else
                    $Message = StringToBinary($Message, 4)                          ; UTF-8 Binary
                    TCPSend($Socket, $Message)
                    If @error Then
                        Return SetError(@error)
                    EndIf
                EndIf
            Next
            Sleep(2000)                                                             ; <-- necessary, so that the socket doesn't disconnect too soon
            TCPCloseSocket($Socket)
            TCPShutdown()
            Return True
    EndSwitch
EndFunc   ;==>_LanMessenger

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...