Sign in to follow this  
Followers 0
E1M1

How to reply tcp w/o creating new connetion?

6 posts in this topic

#1 ·  Posted (edited)

Hello.

Problem I found Is that it's impossible to make 2 scripts communicate eachother using TCP, isn't it? Minimum I found possible is using 2 diferent ports and 4 diferent exes and open ports on both side. 2 that recv and 2 that send packets. I wonder if it's possible to make 2 computers communicate eachother by using only 2 exes - 1 in computer A and other in computer B. I want also use only 1 port. I also want that only server side would require open ports. But I have no idea how to code it. I don't even know if it's possible in autoit.

Could anyone help me making TCP server that would send received message back to client and Client that would send message to server and then display server's reply. I have absolutely no I dea what to do. If anyone could make 2 scripts that communicate each other using UDP w/o requiring 2 ports, I would be thankful.

TCPSend ( $ConnectedSocket, $recv ) Doesnt seem to reply, help says that it needs mainsocket which is returned by TCPConnect But it creates new connection. How could I reply to packet using existing connection?

SERVER

#include <GUIConstantsEx.au3>

Opt('MustDeclareVars', 1)

;==============================================
;==============================================
;SERVER!! Start Me First !!!!!!!!!!!!!!!
;==============================================
;==============================================

Example()

Func Example()
    ; Set Some reusable info
    ; Set your Public IP address (@IPAddress1) here.
;   Local $szServerPC = @ComputerName
;   Local $szIPADDRESS = TCPNameToIP($szServerPC)
    Local $szIPADDRESS = @IPAddress1
    Local $nPORT = 33891
    Local $MainSocket, $GOOEY, $edit, $ConnectedSocket, $szIP_Accepted
    Local $msg, $recv

    ; Start The TCP Services
    ;==============================================
    TCPStartup()

    ; Create a Listening "SOCKET".
    ;   Using your IP Address and Port 33891.
    ;==============================================
    $MainSocket = TCPListen($szIPADDRESS, $nPORT)

    ; If the Socket creation fails, exit.
    If $MainSocket = -1 Then Exit


    ; Create a GUI for messages
    ;==============================================
    $GOOEY = GUICreate("My Server (IP: " & $szIPADDRESS & ")", 300, 200)
    $edit = GUICtrlCreateEdit("", 10, 10, 280, 180)
    GUISetState()


    ; Initialize a variable to represent a connection
    ;==============================================
    $ConnectedSocket = -1


    ;Wait for and Accept a connection
    ;==============================================
    Do
        $ConnectedSocket = TCPAccept($MainSocket)
    Until $ConnectedSocket <> -1


    ; Get IP of client connecting
    $szIP_Accepted = SocketToIP($ConnectedSocket)

    ; GUI Message Loop
    ;==============================================
    While 1
        $msg = GUIGetMsg()

        ; GUI Closed
        ;--------------------
        If $msg = $GUI_EVENT_CLOSE Then ExitLoop

        ; Try to receive (up to) 2048 bytes
        ;----------------------------------------------------------------
        $recv = TCPRecv($ConnectedSocket, 2048)

        ; If the receive failed with @error then the socket has disconnected
        ;----------------------------------------------------------------
        If @error Then ExitLoop

        ; Update the edit control with what we have received
        ;----------------------------------------------------------------
        If $recv <> "" Then
        GUICtrlSetData($edit, $szIP_Accepted & " > " & $recv & @CRLF & GUICtrlRead($edit))
        TCPSend ( $ConnectedSocket, $recv )
        EndIf
    WEnd


    If $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)

    TCPShutdown()
EndFunc   ;==>Example

; Function to return IP Address from a connected socket.
;----------------------------------------------------------------------
Func SocketToIP($SHOCKET)
    Local $sockaddr, $aRet

    $sockaddr = DllStructCreate("short;ushort;uint;char[8]")

    $aRet = DllCall("Ws2_32.dll", "int", "getpeername", "int", $SHOCKET, _
            "ptr", DllStructGetPtr($sockaddr), "int*", DllStructGetSize($sockaddr))
    If Not @error And $aRet[0] = 0 Then
        $aRet = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($sockaddr, 3))
        If Not @error Then $aRet = $aRet[0]
    Else
        $aRet = 0
    EndIf

    $sockaddr = 0

    Return $aRet
EndFunc   ;==>SocketToIP

$recdata = TCPRecv( $ConnectedSocket,4096) doen't get any text. I am unsur wether it's wrong method or wether my server just dont reply.

CLIENT

Opt('MustDeclareVars', 1)

;==============================================
;==============================================
;CLIENT! Start Me after starting the SERVER!!!!!!!!!!!!!!!
;==============================================
;==============================================

Example()

Func Example()
    ; Set Some reusable info
    ;--------------------------
    Local $ConnectedSocket, $szData
    ; Set $szIPADDRESS to wherever the SERVER is. We will change a PC name into an IP Address
;   Local $szServerPC = @ComputerName
;   Local $szIPADDRESS = TCPNameToIP($szServerPC)
    Local $szIPADDRESS = @IPAddress1
    Local $nPORT = 33891

    ; Start The TCP Services
    ;==============================================
    TCPStartup()

    ; Initialize a variable to represent a connection
    ;==============================================
    $ConnectedSocket = -1

    ;Attempt to connect to SERVER at its IP and PORT 33891
    ;=======================================================
    $ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)

    ; If there is an error... show it
    If @error Then
        MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)
        ; If there is no error loop an inputbox for data
        ;   to send to the SERVER.
    Else
        ;Loop forever asking for data to send to the SERVER
        Dim $recdata
        While 1
            ; InputBox for data to transmit
            If $recdata <> "" Then MsgBox(0,0,$recdata)
            $szData = InputBox("Data for Server", @LF & @LF & "Enter data to transmit to the SERVER:")

            ; If they cancel the InputBox or leave it blank we exit our forever loop
            If @error Or $szData = "" Then ExitLoop

            ; We should have data in $szData... lets attempt to send it through our connected socket.
            TCPSend($ConnectedSocket, $szData)
            $recdata = TCPRecv( $ConnectedSocket,4096)

            ; If the send failed with @error then the socket has disconnected
            ;----------------------------------------------------------------
;~             If @error Then ExitLoop
        WEnd
    EndIf
EndFunc   ;==>Example

Thanks in advance

Edited by E1M1

edited

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Problem I found Is that it's impossible to make 2 scripts communicate eachother using TCP, isn't it?

It is possible if im not wrong, i had similar problem but i forgot how i solwed it (for UDP i realy dono)

The best i can offer to you is my old client and mobtracker scripts, i striped code from client and it return tooltip but i dont have nerves to strip code from server at the moment, if you have nerves than goodluck to you :graduated:

Il try tomoro to strip the code from server if i finde time or not if someone else help you or you menage to stripit yourself

Edit: striped alot of code from server, server send random numbers from 200-300, client send random number from 1-10 and his identification (this is on 1 comp comunication, for 2 comps on network i must look tomoro on second comp but if i remamber correctly nothing sugnificant is needed to b changed)

client

TCPStartup ( )
$ConnectedSocket = TCPConnect ( @IPAddress1 , 33891 )
While 1
    $reply = BinaryToString ( TCPRecv ( $ConnectedSocket , 10000000 , 1 ) )
    If $reply <> ""Then ToolTip( $reply )
    TCPSend ( $ConnectedSocket , DriveGetSerial("c:\") & "$" & String(Random(1,10,1))& "$")
Wend

server

#Include <GuiListBox.au3>
#include <GuiListView.au3>
Dim $array[100][2],$f
TCPStartup()
$MainSocket = TCPListen(@IPAddress1, 33891)
If $MainSocket = -1 Then Exit
GUICreate("My STATS", 800, 600 ,0 ,0)
GUICtrlCreateTab(10, 5, 780, 100)
GUICtrlCreateTabItem("Connection Monitor")
$hlistview = GUICtrlCreateListView("", 10,50, 780, 540)
_GUICtrlListView_AddColumn($hListView, "Identification", 90)
_GUICtrlListView_AddColumn($hListView, "msg", 34)
GUISetState()
While 1
    $msg = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Then
        ExitLoop
    EndIf
    For $r = 0 to UBound($array) - 1
        If $array[$r][0] <> "" Then
            $recv = TCPRecv($array[$r][0], 1000000)
            If $recv <> "" Then 
                $data = StringSplit($recv,"$")
                _GUICtrlListView_InsertItem($hListView, $data[1], 0)
                _GUICtrlListView_AddSubItem($hListView, 0, $data[2], 1, 1)
            EndIf
            TCPSend($array[$r][0],String(Random(200,300,1)))
        EndIf
    Next
    newclient()
WEnd
TCPShutdown()
Func newclient()
    $ConnectedSocket = TCPAccept($MainSocket)
    If $ConnectedSocket <> -1 Then
        $array[$f][0] = $ConnectedSocket
        $f += 1
    EndIf
EndFunc
Edited by bogQ

TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Thank you. I didn't funny understand that array thing. $array[$r][0]. But Your code uses functions more effective than help example.

Edited by E1M1

edited

Share this post


Link to post
Share on other sites

before i striped code from mob server, $array[$r][0] what's there to accept more than one client, using driveserial as identification. So it was designed to allow more than one client to connect on server and to keep track of them (looping in $array to trigger all connections).

The only problem at the moment in script is that if client send two times data

DriveGetSerial("c:\") & "$" & String(Random(1,10,1))& "$")

and server is late in reaeading it will display only first data becose of

$data = StringSplit($recv,"$")

_GUICtrlListView_InsertItem($hListView, $data[1], 0)

_GUICtrlListView_AddSubItem($hListView, 0, $data[2], 1, 1)

You can solve that with for $x = 1 to $data[0] step 2

and some minor ajustment to the

_GUICtrlListView_InsertItem


TCP server and client - Learning about TCP servers and clients connection
Au3 oIrrlicht - Irrlicht project
Au3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related)



460px-Thief-4-temp-banner.jpg
There are those that believe that the perfect heist lies in the preparation.
Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.

 

Share this post


Link to post
Share on other sites

thanks again.


edited

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

How to solve this? (I also want to keep multi client support)

#include <Array.au3>
#include <Constants.au3>
#include-once
Dim $array[100][2],$f
TCPStartup()
$MainSocket = TCPListen(@IPAddress1, 33891)
If $MainSocket = -1 Then Exit
While 1
    For $r = 0 to UBound($array) - 1
        If $array[$r][0] <> "" Then
            $recv = TCPRecv($array[$r][0], 1000000)
            If $recv <> "" Then
            $ans = CommandParse($recv)
            TCPSend($array[$r][0],String($ans))
            EndIf
        EndIf
    Next
    newclient()
WEnd
TCPShutdown()
Func newclient()
    $ConnectedSocket = TCPAccept($MainSocket)
    If $ConnectedSocket <> -1 Then
        $array[$f][0] = $ConnectedSocket
        $f += 1
    EndIf
EndFunc


Func CommandParse($sCommand)
    $array = StringSplit($sCommand," ")
    Switch $array[1]
        Case "cmd"
            $alltext = ""
            Local $foo = Run(@ComSpec & " /c " & _ArrayToString($array," ",2), @SystemDir, @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
            ConsoleWrite("cmd: "&_ArrayToString($array," ",2)&@CRLF)
            Local $line
            For $n = 1 To 3 Step 0
                $line = StdoutRead($foo)
                If @error Then ExitLoop
                $alltext = $alltext & $line
            Next
            ConsoleWrite("All text"&$alltext&@CRLF)
            Return $alltext
    EndSwitch
EndFunc   ;==>CommandParse

C:\src19022010\plugins\remotecommand\tcp.au3 (14) : ==> Array variable has incorrect number of subscripts or subscript dimension range exceeded.:

TCPSend($array[$r][0],String($ans))

TCPSend(^ ERROR

client

TCPStartup ( )
$ConnectedSocket = TCPConnect ( @IPAddress1 , 33891 )
While 1
    $reply = BinaryToString ( TCPRecv ( $ConnectedSocket , 10000000 , 1 ) )
    If $reply <> ""Then ToolTip( $reply )
    TCPSend ( $ConnectedSocket ,"cmd help")
Wend
Edited by E1M1

edited

Share this post


Link to post
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
Sign in to follow this  
Followers 0