Jump to content

TCP UDF, Event driven!


Kip
 Share

Recommended Posts

Greeting all,

Kip, this UDF looks pretty cool. I'm hoping to put it to good use.

I've got a few questions if anyone would be willing to help me out here. Please keep in mind I'm new to programming, so the code may appear "spagetti like", I'll try to refine it later.

I'm writing 2 scripts...

Script "A" (Server script) will run on my file server and will:

1. Detect when a thumb drive is inserted in a USB port (on the server) then

2. Ping "key" systems and those that are successfully pinged, launch client script on those systems using PSEXEC then

3. Make sure one "specific" client has established a connection to the server, wait at most 10min for it to connect, and if after 10min it hasn't connected make sure least one other remote client has a connection to the server then

4. Send message to client(s) letting them know the thumb drive was inserted on date/time and that backup has begun then

5. Begin backing up data from a server hard drive to the thumb drive then

6. Store various backup events into a variable and export those on the fly to connected clients (or the entire "log of events" to newly connected clients) then

7. Finish backup, using Microsoft's devcon utility "disconnect" the thumb drive then

8. Send message to clients it's safe to remove the thumb drive.

9. Once thumb drive has been removed, send message to all clients telling them the thumb drive was removed, ok to close client program.

Script "B" (Client(s) script) will run possible multiple clients.

1. Establish connection to server.

2. Send it's computername to server for it to evaluate if the connecting client is the "specific" client it really wants.

3. Receive event messages from the server

I've gotten the thumb drive detection/backup portion working good, just need help on the following.

I need the server and clients to talk back and forth to each other (clients to server, server to clients, not clients to clients). I basically want that "specific" client to send it's computername to the server, that way the server will know its connected so it can either proceed with the backup OR wait 10min and take whatever other clients are connected before proceeding with the backup. Basically I've got 1 person that is responsible for backups, but a few "key" others would like to make sure the server is backed up (receiving status updates from the server). If that 1 "specific" person is off on that day, one of those "key" others would be responsible for performing the backup, hence the message would need to be sent to them.

I'd need help understanding how the _TCP_Server_ClientList() function works, can someone provide an example of it's usage?

Here are the example scripts, that I've modified, in an attempt to understand how to make the client and server talk BACK AND FORTH. I've only setup the client script (unsuccessfully) to be able to send text back to the server via a GUI-Input and using a send button. I think the script isn't working because of the "Select - Case" function for detecting if the button was pushed. I played around with various ideas, none of which has made it work.

Can someone tell me/correct what I'm doing wrong?

Don't forget that I'd also like an example on the _TCP_Server_ClientList() function.. :(

Thanks much!!!!

Server Script

#include "TCP.au3"
#include "array.au3"


 $hGui = GUICreate("Client Messages",300,200,100,100)
        GUISetState(@SW_SHOW)
 $Edit = GuiCtrlCreateEdit("",5,5,290,190)

$hClient = _TCP_Client_Create(@IPAddress2, 89); Create a client to allow the server to act as a client for receiving messages from actual clients, used a different port hoping that would allow it to work.
 $hServer = _TCP_Server_Create(88); A server. Tadaa!

 _TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient"); Whooooo! Now, this function (NewClient) get's called when a new client connects to the server.
 _TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect"); And this,... this will get called when a client disconnects.
 _TCP_RegisterEvent($hServer, $TCP_RECEIVE, "Received")

 $msg = GUIGetMsg()

 While 1
    sleep(5)
 WEnd

Func Received($hSocket, $sReceived, $iError); And we also registered this! Our homemade do-it-yourself function gets called when something is received.
     GUICtrlSetData($Edit, $sReceived)
 EndFunc

 Func NewClient($hSocket, $iError); Yo, check this out! It's a $iError parameter! (In case you didn't noticed: It's in every function)
 GUICtrlSetData($Edit,"New client connected."&@CRLF&"Sending Greeting to Client")

 _TCP_Send($hSocket, "Hello New Client"&@CRLF)
 _TCP_Send($hSocket, "This is the 2nd Message"&@CRLF)
 EndFunc

 Func Disconnect($hSocket, $iError); Damn, we lost a client. Time of death: @Hour & @Min & @Sec :P
 GUICtrlSetData($Edit,"Client disconnected.")

 EndFunc

Client Script

#include "TCP.au3"
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

 $hGui = GUICreate("Server Messages",300,225,100,305)
        GUISetState(@SW_SHOW)
 $Edit = GuiCtrlCreateEdit("",5,5,290,190)
        GuiCtrlCreateLabel("Message",5,202,50,20)
 $Message = GUICtrlCreateInput("",55,200,180,20)
 $SendButton = GUICtrlCreateButton("Send",240,200,50,20)


 $hClient = _TCP_Client_Create(@IPAddress1, 88); Create the client. Which will connect to the local ip address on port 88
 $hServer = _TCP_Server_Create(89)

 _TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received"); Function "Received" will get called when something is received
 _TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected"); And func "Connected" will get called when the client is connected.
 _TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected"); And "Disconnected" will get called when the server disconnects us, or when the connection is lost.


    $msg = GUIGetMsg()

;Try to do a "select - case" to recognize if the button was pushed, read the data and send it to the server.
    Select
        Case $msg = $GUI_EVENT_CLOSE
            Exit
        Case $msg = $SendButton
            _TCP_RegisterEvent($hClient, $TCP_Send, "SendMessage")
    EndSelect

 While 1
   Sleep(5); just to keep the program running
 WEnd

Func SendMessage($hSocket, $iError); Yo, check this out! It's a $iError parameter! (In case you didn't noticed: It's in every function)
    _TCP_Send($hSocket, GuiCtrlRead($Message)&@CRLF)
 EndFunc


 Func Connected($hSocket, $iError); We registered this (you see?), When we're connected (or not) this function will be called.

     If not $iError Then; If there is no error...
         GUICtrlSetData($Edit, "Connected!")
     Else; ,else...
         GUICtrlSetData($Edit, "Could not connect. Are you sure the server is running?")
     EndIf

 EndFunc


 Func Received($hSocket, $sReceived, $iError); And we also registered this! Our homemade do-it-yourself function gets called when something is received.
     GUICtrlSetData($Edit, $sReceived)

 Func Disconnected($hSocket, $iError); Our disconnect function. Notice that all functions should have an $iError parameter.
     GUICtrlSetData($Edit, "Connection closed or lost.")
 EndFunc
Link to comment
Share on other sites

  • 3 weeks later...

Hello,

I am having some problems with a client script that send logs to a server script. Its inconsistent, sometimes the data just doesn't get sent. If I telnet to the server it always receive the data. Multiple clients can be connected to server and work fine for while. Sometime a client will connect and never send anything until its restarted. Sometimes a client that worked fine for a few logs over a few hours will fail to send just one log.

The main script is a gui that send logs to the server when other functions are called.

The client

#cs ----------------------------------------------------------------------------

    AutoIt Version: 3.3.4.0
    Author:         myName

    Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

;ToolTip("CLIENT: Connecting...",10,10)

$hClient = _TCP_Client_Create("142.101.242.130", 88); Create the client. Which will connect to the local ip address on port 88

_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received"); Function "Received" will get called when something is received
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected"); And func "Connected" will get called when the client is connected.
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected"); And "Disconnected" will get called when the server disconnects us, or when the connection is lost.

Func Connected($hSocket, $iError); We registered this (you see?), When we're connected (or not) this function will be called.
    If Not $iError Then; If there is no error...
    ;   ToolTip("CLIENT: Connected!",10,10); ... we're connected.
    Else; ,else...
    ;   ToolTip("CLIENT: Could not connect. Are you sure the server is running?",10,10); ... we aren't.
    EndIf

EndFunc   ;==>Connected

#cs ----------------------------------------------------------------------------
    SendToServer
    Send the received strings to the server along with a timestamp and the username

    $FuncName should be the name of the function calling SendToServer
    $StringToSend1 to 4 are the optional strings sent by the calling function to log
#ce ----------------------------------------------------------------------------
Func SendToServer($FuncName, $StringToSend1 = "", $StringToSend2 = "", $StringToSend3 = "", $StringToSend4 = "")
    If $StringToSend2 <> "" Then $StringToSend1 = $StringToSend1 & """,""" & $StringToSend2
    If $StringToSend3 <> "" Then $StringToSend1 = $StringToSend1 & """,""" & $StringToSend3
    If $StringToSend4 <> "" Then $StringToSend1 = $StringToSend1 & """,""" & $StringToSend4
    If $StringToSend1 <> "" Then
        sleep(50)
        _TCP_Send($hClient, """" & _Now() & """,""" & @UserName & """,""" & $FuncName & """,""" & $StringToSend1 & """" & @CRLF)
    Else
        sleep(50)
        _TCP_Send($hClient, """" & _Now() & """,""" & @UserName & """,""" & $FuncName & """" & @CRLF)
    EndIf
EndFunc   ;==>SendToServer


Func Received($hSocket, $sReceived, $iError); And we also registered this! Our homemade do-it-yourself function gets called when something is received.
    ; ToolTip("CLIENT: We received this: "& $sReceived, 10,10); (and we'll display it)
EndFunc   ;==>Received

Func Disconnected($hSocket, $iError); Our disconnect function. Notice that all functions should have an $iError parameter.
    ;ToolTip("CLIENT: Connection closed or lost.", 10,10)
EndFunc   ;==>Disconnected

The server

#include "TCP.au3"
#include <Date.au3>
#include <File.au3>

;ToolTip("SERVER: Creating server...", 10, 30)

$hServer = _TCP_Server_Create(88); A server. Tadaa!

_TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient"); Whooooo! Now, this function (NewClient) get's called when a new client connects to the server.
_TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect"); And this,... this will get called when a client disconnects.
_TCP_RegisterEvent($hServer, $TCP_RECEIVE, "ReceivedServer")
While 1
    sleep(10)
WEnd

Func NewClient($hSocket, $iError); Yo, check this out! It's a $iError parameter! (In case you didn't noticed: It's in every function)

    ;ToolTip("SERVER: New client connected.", 10, 30)

    ;_TCP_Send($hSocket, "Bleh!"); Sending: "Bleh!" to the new client. (Yes, that's right: $hSocket is the socket of the new client.)

EndFunc   ;==>NewClient

Func Disconnect($hSocket, $iError); Damn, we lost a client. Time of death: @Hour & @Min & @Sec :P

    ;ToolTip("SERVER: Client disconnected.", 10, 30); Placing a tooltip right under the tooltips of the client.

EndFunc   ;==>Disconnect


Func ReceivedServer($hSocket, $sReceived, $iError); And we also registered this! Our homemade do-it-yourself function gets called when something is received.
    $file = _DateToMonth(@MON)&" "&@YEAR&".csv"
    FileWriteLine($file,$sReceived)
    sleep(5)
EndFunc   ;==>ReceivedServer

#cs ----------------------------------------------------------------------------

    AutoIt Version: 3.3.4.0
    Author:         myName

    Script Function:
    Template AutoIt script.

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

Any help would be appreciated

Link to comment
Share on other sites

Hello,

I am having some problems with a client script that send logs to a server script. Its inconsistent, sometimes the data just doesn't get sent. If I telnet to the server it always receive the data. Multiple clients can be connected to server and work fine for while. Sometime a client will connect and never send anything until its restarted. Sometimes a client that worked fine for a few logs over a few hours will fail to send just one log.

I'm doing something similar to yours but not in production yet. As my connection will be over te net I've adding "reconnect" code so if it drops out the conneciton will be remade.

With the example code you've sent there is no local log file created of the conneciton. I'd suggest that be your first thing to try.

Check if the connection is dropping out

Check that the SEND function is being called

Check that the original connection is being made

There are many things that could be causing your problem and "local" log files are the best place to start.

Good Luck

Link to comment
Share on other sites

grandim,

Please try to set delay of an about 500 milisecond before you send data. let me know if data will always be sent.

I think that I have same situation.

The delay works for me but I did not tested it yet deeply.

Be Green Now or Never (BGNN)!

Link to comment
Share on other sites

I'm doing something similar to yours but not in production yet. As my connection will be over te net I've adding "reconnect" code so if it drops out the conneciton will be remade.

With the example code you've sent there is no local log file created of the conneciton. I'd suggest that be your first thing to try.

Check if the connection is dropping out

Check that the SEND function is being called

Check that the original connection is being made

There are many things that could be causing your problem and "local" log files are the best place to start.

Good Luck

I will try to remove the comments on the tooltips of the client to get some troubleshooting data.

Your client doesn't loop anything. It starts up, and before the server can respond back, it shuts down again. I guess you're just lucky it works some times.

TCP.au3 and TCPclient.au3 are included in a GUI based script that has its own loop.

grandim,

Please try to set delay of an about 500 milisecond before you send data. let me know if data will always be sent.

I think that I have same situation.

The delay works for me but I did not tested it yet deeply.

I'll give this a try and let you know.

Edited by grandim
Link to comment
Share on other sites

  • 2 weeks later...

What method do you suggest for detecting if the connection is active, and if not, reconnecting? I'm pretty sure someone already asked this question in broken English and didn't receive an answer. I implemented the following and ran into an error:

TCP.au3 (453) : ==> "ReDim" used without an array variable.:
ReDim $__TCP_SOCKETS[UBound($__TCP_SOCKETS)+1][7]
ReDim ^ ERROR
Relevant client code:

;Variables
Global $server_ip = '192.168.1.7'
Global $hClient, $connected, $zzz

;Functions
Func DebugMessage($message)
    ConsoleWrite(_Date_Time_SystemTimeToDateTimeStr(_Date_Time_GetLocalTime()) & ' - ' & $message & @LF)
EndFunc
Func Connected($hSocket, $iError)
    If not $iError Then
        DebugMessage("CLIENT: Connected!")
        $connected = True
    Else
        DebugMessage("CLIENT: Could not connect. Are you sure the server is running?")
        _TCP_Client_Stop($hSocket)
        $connected = False
    EndIf
EndFunc
Func Received($hSocket, $sReceived, $iError)
    DebugMessage("CLIENT:" & $hSocket & ": We received this: "& $sReceived)
EndFunc
Func Disconnected($hSocket, $iError)
    DebugMessage("CLIENT: Connection closed or lost." & $hSocket)
    _TCP_Client_Stop($hSocket)
    $connected = False
EndFunc

$hClient = _TCP_Client_Create($server_ip, 42981)
DebugMessage("CLIENT: Connecting...")
_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received")
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected")
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected")

;Loop
While 1
    Sleep(10) ; Loop 100 times per second, bar the process time any triggered event takes
    $zzz += 10
    If $zzz = 5000 Then ; Do something every 5 seconds
        If $connected = True Then
            DebugMessage("CLIENT (" & $hClient & '): Sending something...')
            DebugMessage('TCPSend result: ' & _TCP_Send($hClient, 'Keep-Alive'))
        Else
            $hClient = _TCP_Client_Create($server_ip, 42981)
            DebugMessage("CLIENT: Connecting...")
            _TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected")
        EndIf
        $zzz = 0
    EndIf
WEnd

Am I correct in understanding that I need to _TCP_RegisterEvent every after every _TCP_Client_Create?

Link to comment
Share on other sites

  • 4 weeks later...

Hi Kip,

I think I found a bug, but I do not know how to fix it.

But, first lets agree that its a bug :idea:

The bug is about the _TCP_Send() function that send data to the wrong socket in certain condition as it is described bellow.

Steps to reproduce:

Environment:

1) Set the IP string in the _TCP_Client_Create() function of the client script.

2) Compile as a console the server and client scripts(Please utilize the Aut2Exe app.).

Use case:

Note: In order to test it you will need two clients and one server, better to try on different machine but not must.

1) Launch the server

2) Launch Client A.

Note: The output on the Server console to be expected is:

New Client=516

Server message sent to socket:516

Sockets list(SendMessage):1|516

3) Launch Client B.

Note: The output on the Server console to be expected is:

New Client=516

Server message sent to socket:516

Sockets list(SendMessage):1|516

New Client=504

Server message sent to socket:504

Sockets list(SendMessage):2|516|504

4) Shout down client A:

Note: The output on the Server console to be expected is:

New Client=516

Server message sent to socket:516

Sockets list(SendMessage):1|516

New Client=504

Server message sent to socket:504

Sockets list(SendMessage):2|516|504

Disconnect=516

5) Launch Client A:

Note: The output on the Server console to be expected is:

New Client=516

Server message sent to socket:516

Sockets list(SendMessage):1|516

New Client=504

Server message sent to socket:504

Sockets list(SendMessage):2|516|504

Disconnect=516

New Client=516

Server message sent to socket:504

Sockets list(SendMessage):2|504|516

The problem: As you can see from the last output, the new client socket is 516 but the

message was sent to socket 504.

The client script:

#include "TCP.au3"
#include <Array.au3>
$hClient = _TCP_Client_Create("16.59.42.42", 48123)

_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received")
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected")
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected")
_TCP_RegisterEvent($hClient, $TCP_SEND, "SendMessage")

While 1
    Sleep(15)
WEnd

Func Connected($hSocket, $iError)
    
    If Not $iError Then
        _TCP_Send($hSocket, "ClientConnected" )
    Else
         ToolTip("CLIENT: Could not connect. Are you sure the server is running?",10,10); ... we aren't.
    EndIf
EndFunc   ;==>Connected

Func Received($hSocket, $sReceived, $iError)
    If $sReceived = "ServerReply" Then 
        _TCP_Send($hSocket, "ClientResponse" )
    EndIf
EndFunc   ;==>Received

Func Disconnected($hSocket, $iError)
    
EndFunc   ;==>Disconnected

Func SendMessage($hSocket, $iError)
    ConsoleWrite("SendMessage: Message sent to Socket=" & $hSocket & @CRLF)
EndFunc   ;==>SendMessage

Func _PrintSocketsList($FunctionName)
    Local $ssArray

    $ssArray = _TCP_Server_ClientList()
    Consolewrite( "Sockets list("&$FunctionName&"):" & _ArrayToString($ssArray) & @CRLF)
EndFunc

The Server script is:

#include "TCP.au3"
#include <Array.au3>

$hServer = _TCP_Server_Create(48123)

_TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient")
_TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect")
_TCP_RegisterEvent($hServer, $TCP_RECEIVE, "Received")
_TCP_RegisterEvent($hServer, $TCP_SEND, "SendMessage")

While 1
    Sleep(15)
WEnd

Func NewClient($hSocket, $iError)
    ConsoleWrite ("New Client=" & $hSocket & @CRLF )
EndFunc

Func Disconnect($hSocket, $iError)
    ConsoleWrite ("Disconnect=" & $hSocket & @CRLF )
EndFunc

Func Received($hSocket, $sReceived, $iError)
    
    If $sReceived="ClientConnected" Then
        _TCP_Send($hSocket, "ServerReply" )
    EndIf
EndFunc

Func SendMessage($hSocket, $iError)
    ConsoleWrite("Server message sent to socket:" & $hSocket & @CRLF)
    _PrintSocketsList("SendMessage")
EndFunc 

Func _PrintSocketsList($FunctionName)
    Local $ssArray
    $ssArray = _TCP_Server_ClientList()
    Consolewrite( "Sockets list("&$FunctionName&"):" & _ArrayToString($ssArray) & @CRLF)
EndFunc
Edited by lsakizada

Be Green Now or Never (BGNN)!

Link to comment
Share on other sites

Hi Kip,

I think I found a bug, but I do not know how to fix it.

But, first lets agree that its a bug :idea:

The bug is about the _TCP_Send() function that send data to the wrong socket in certain condition as it is described bellow.

Everybody:

Please don't say you have found a bug in my script whenever something isn't working as expected. Everytime someone said that, it turned out to be their own fault.

---

You're saying that _TCP_Send() has a bug. Funny... very funny.

If you look at the source you see this:

Func _TCP_Send($hSocket, $sText)
    Return TCPSend($hSocket, $sText)
EndFunc ;==>_TCP_Send

It is just a synonym for TCPSend(). Unless the author of that function made a mistake, I'm pretty sure it's you.

Edit:

You are interpreting the callbacks wrong: the $TCP_SEND callback gets called whenever the other side of the connection is ready to receive data, not when a call to TCPSend() has been completed succesfully.

Edited by Kip
Link to comment
Share on other sites

I didn't say that the _TCP_Send() function has a bug, obviously.

But, I said that I suspect that the wrong socket got the data after calling _TCP_Send() in the scenario that I provided. hence thats why I said that we need to agree about it.

Now, to be practical, what's wrong with the scripts? Did you run it at all?

I totally did not understand your answer in the "Edit:" part.

If you think the scripts are wrong then what is wrong there?

Edited by lsakizada

Be Green Now or Never (BGNN)!

Link to comment
Share on other sites

I didn't say that the _TCP_Send() function has a bug, obviously.

But, I said that I suspect that the wrong socket got the data after calling _TCP_Send()

:

The bug is about the _TCP_Send() function that send data to the wrong socket in certain condition as it is described bellow.

Everything works fine... obviously.

(1) Now, to be practical, what's wrong with the scripts? (2) Did you run it at all?

(3) I totally did not understand your answer in the "Edit:" part.

(4) If you think the scripts are wrong then what is wrong there?

1: Nothing

2: Nope, don't need to.

3: Too bad... that's where the answer is.

4: The scripts are fine, you're just interpreting the $TCP_SEND callbacks wrong. They don't get called when something has been send, but when the other side of the connection is ready for more data.

(The "other side of the connection" is the server for client scripts, and a client for a server script.)

Edited by Kip
Link to comment
Share on other sites

  • 3 weeks later...

If I wanted a client to keep trying to connect until it was successful, where would I put the _TCP_RegisterEvent() functions? Would I only need to call them once in the script?

For example:

$hClient = _TCP_Client_Create($sIP, $iPort)
_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "_InfoReceived")
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "_ClientConnected")
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "_ClientDisconnected")

Func _ClientConnected($hSocket, $iError)
    If Not $iError Then
        ;ConsoleWrite("Client Connected!" & @CRLF)
    Else
        Do
            $hClient = _TCP_Client_Create($sIP, $iPort)
            _TCP_RegisterEvent($hClient, $TCP_RECEIVE, "_InfoReceived")
            _TCP_RegisterEvent($hClient, $TCP_CONNECT, "_ClientConnected")
            _TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "_ClientDisconnected")
            Sleep(1000)
        Until ;Until what?
    EndIf
EndFunc

Should I check the value of $hClient BEFORE Registering Events, and register them only if it equals a certain value? If so, what value would that be?

Link to comment
Share on other sites

If I wanted a client to keep trying to connect until it was successful, where would I put the _TCP_RegisterEvent() functions? Would I only need to call them once in the script?

For example:

$hClient = _TCP_Client_Create($sIP, $iPort)
_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "_InfoReceived")
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "_ClientConnected")
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "_ClientDisconnected")

Func _ClientConnected($hSocket, $iError)
    If Not $iError Then
        ;ConsoleWrite("Client Connected!" & @CRLF)
    Else
        Do
            $hClient = _TCP_Client_Create($sIP, $iPort)
            _TCP_RegisterEvent($hClient, $TCP_RECEIVE, "_InfoReceived")
            _TCP_RegisterEvent($hClient, $TCP_CONNECT, "_ClientConnected")
            _TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "_ClientDisconnected")
            Sleep(1000)
        Until ;Until what?
    EndIf
EndFunc

Should I check the value of $hClient BEFORE Registering Events, and register them only if it equals a certain value? If so, what value would that be?

Since there is no point of registring the events without a valid socket you should wait to register them until you recieve a successful message registring your client. Your re-try timer needs to be implemented in a way that suits your applications (guitimers, dlltimers or a simple sleep event) - And yes you need only to register them once (you could however reregister them if you want to change the behaviour of your application during execution).

Quick and dirty:

$hClient = False
While $hClient = False
   $hClient = _TCP_Client_Create($sIP, $iPort)
   Sleep(5000)
Wend
_TCP_RegisterEvent($hClient, $TCP_RECEIVE, "_InfoReceived")
_TCP_RegisterEvent($hClient, $TCP_CONNECT, "_ClientConnected")
_TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "_ClientDisconnected")

Ig

Link to comment
Share on other sites

  • 3 weeks later...

First off, great UDF, 6 stars at least.

I'm trying to make a P2P program. Before you say: YOU CANNOT CREATE A CLIENT AND A SERVER IN THE SAME SCRIPT,

I'm going to say that is not my intention.

I intend to use your UDF as the server side of the program (managing incoming connection requests), then initiate connections (as P2P programs do as well) using raw TCP functions embedded in Autoit.

Is this possible?

And secondly, Is it possible to 'inject' the sockets and connection variables that have been created from the Raw TCP functions, into the functions in your UDF, so I can just use the server functions to manage recieving and sending data?

And if so, How?

I will post the code so far upon request. It's long.

Thanks for any help,

Hypoz.

ongoing projects:-firestorm: Largescale P2P Social NetworkCompleted Autoit Programs/Scripts: Variable Pickler | Networked Streaming Audio (in pure autoIT) | firenet p2p web messenger | Proxy Checker | Dynamic Execute() Code Generator | P2P UDF | Graph Theory Proof of Concept - Breadth First search

Link to comment
Share on other sites

First off, great UDF, 6 stars at least.

I'm trying to make a P2P program. Before you say: YOU CANNOT CREATE A CLIENT AND A SERVER IN THE SAME SCRIPT,

I'm going to say that is not my intention.

I intend to use your UDF as the server side of the program (managing incoming connection requests), then initiate connections (as P2P programs do as well) using raw TCP functions embedded in Autoit.

1) Is this possible?

2) And secondly, Is it possible to 'inject' the sockets and connection variables that have been created from the Raw TCP functions, into the functions in your UDF, so I can just use the server functions to manage recieving and sending data?

And if so, How?

I will post the code so far upon request. It's long.

Thanks for any help,

Hypoz.

1. Should be possible.

2. Are those 'sockets and connection variables' from a client or a server?

Link to comment
Share on other sites

1. Should be possible.

2. Are those 'sockets and connection variables' from a client or a server?

Answering your question:

The sockets and connection variables are just an array storing the handles, IP's, and other info of connected Nodes in the P2P network. I want to pass this information into your UDF variables, so I can use the Event driven UDF functions to manage these connections.

Ok. Here is a small segment of the code so far to connect to another node using Raw TCP functions.

Notice it does:

1. Reads a random node IP from an ini file that was stored on the internet, which has been downloaded previously. This file is constantly being updated with the current IP of a node (Damn Dynamic Ip's), which are all numbered.

2. Checks to see if it is already connected to that node,if it is in LAN, or if it is it's self.

3. Attempts to Connect to it.

4. Checks to see if connection was successful, and if so, stores it in an array.

Here is the code:

Func Connectsupernode()
    ;pick a supernode
    $IPcon = "192.168.1.255"
    $nodeid = Random( 0 , $registercountsupernode, 1)
    global $connectnode = IniRead( "registry.ini", "supernoderegister", $nodeid, "192.168.1.11"); Public IP
    global $nodelocal = IniRead( "registry.ini", "supernodelocalregister", $nodeid, "192.168.1.11");local IP
    For $f = 0 to $maxconnections step 1 ;checks to see if already connected, in LAN, or is it'self
        if $connectnode = $clientslotIP[$f] then return 2 ;this is array holding Ip's of connections
        if $connectnode = $globalip then
            if $connectnode = @IPAddress1 then return 3
            if $nodelocal <> @IPAddress1 then $IPcon = $nodelocal
        Else
            $IPcon = $connectnode ; Stores public IP ready to attempt a connection.
        EndIf
    Next
    ; Find an empty connection slot in array
        Sleep(200)
    $newConnNum = -1
    For $x = 0 To $maxconnections
        If $clientslothandle[$x] = -1 Then
            $newConnNum = $x
            ExitLoop
        EndIf
    Next
    If $newConnNum = -1 Then Return 0
    $newConn = TCPConnect($IPcon, $MessengerPort)
        Sleep(200)
    If $newConn = -1 Then Return 0 ; Connection failed
    $clientslothandle[$newConnNum] = $newconn
    $clientslottype[$newConnNum] = 1
    $clientslotencrypt[$newConnNum] = 1
    $clientslotID[$newConnNum] = -1
    $clientslotIP[$newConnNum] = $ipcon
    $clientslotname[$newConnNum] = -1
    global $supernodesconnected1 = $supernodesconnected + 1
    global $supernodesconnected = $supernodesconnected1
    Return 1
EndFunc

My question is:

What variables will I have to declare to add this new connection into your TCP variables, so that you Event driven UDF will manage this connection as well?

Thanks in Advance:

Hypoz.

ongoing projects:-firestorm: Largescale P2P Social NetworkCompleted Autoit Programs/Scripts: Variable Pickler | Networked Streaming Audio (in pure autoIT) | firenet p2p web messenger | Proxy Checker | Dynamic Execute() Code Generator | P2P UDF | Graph Theory Proof of Concept - Breadth First search

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...