Jump to content
Sign in to follow this  
ripdad

WSA_NBTCP v1.00 UDF

Recommended Posts

_WSA_TCPRecv seems to work also with TCPServer UDF "sometimes" which I cannot figure my self what is getting in the way to cause the receiving of @error 10060 or @error -1 as in most cases ..

Share this post


Link to post
Share on other sites

10060 is a timeout error. You may have to set the timeout higher. Or perhaps you might need to disable it by setting it to 0 (which is the equivalent as keep-alive).

-1 is a DLL error (which should not happen). I have never experienced that error either -- very strange.

Perhaps it's because the socket is no longer valid.

That's the reason it's good to close the socket after an error occurs.

You can always re-initiate a connection.

 


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

Share this post


Link to post
Share on other sites

Deye,

I had some time to get familiar with the two UDF's using AdlibRegister.
It seems that lowering the default of 250ms to 50ms would help speed it up.

Also, I noticed there wasn't any error checking in the 3 TCPSend() functions.

I rewrote the __TCPServer_Recv().
You can also rewrite the __TCPClient_Recv() the same way.

Before I was trying to stay with the format of the original one on the client.

This is the way I think it "should" work, with only one _WSA_TCPRecv call.
Let me know if it helps improve your issue. (comments included)

Func __TCPServer_Recv()
    Local $nBytesReceived, $nError, $sData, $sRecv
    ;
    For $i = 1 To $_TCPServer_MaxClients
        If $__TCPServer_Sockets[$i] < 1 Then
            ContinueLoop
        EndIf
        ;
        $sData = ''; <- clear previous data
        ;
        For $j = 1 To 3; <- three tries. (this is needed because usually the first one or two recv calls is blank)
            $sRecv = _WSA_TCPRecv($__TCPServer_Sockets[$i], 65536, 1, 10)
            $nError = @error
            $nBytesReceived = @extended
            ;
            If $nError Then
                ConsoleWrite('__TCPServer_Recv Error: ' & $nError & @CRLF)
                __TCPServer_KillConnection($i)
                ExitLoop
            ElseIf $nBytesReceived Then
                $sData &= BinaryToString($sRecv); <- gather incoming data
                $j = 0; <- reset to continue loop while receiving data
            Else
                ; <- no bytes received
            EndIf
            Sleep(10); <- 10 milliseconds (if the loop runs in microseconds, it won't be efficient in the long run)
        Next
        ;
        If $sData <> '' Then; <- includes any data gathered before an error occurred
            Call($_TCPServer_OnReceiveCallback, $__TCPServer_Sockets[$i], _TCPServer_SocketToIP($__TCPServer_Sockets[$i]), $sData, $__TCPServer_Pars[$i])
        EndIf
    Next
EndFunc

 

-edit-

Here is one of the TCPSend() functions as an example of how I think it should be done.

Func _TCPServer_Send($iSocket, $sData)
    If $iSocket < 1 Then
        Return SetError(-1, 0, 0); <- invalid socket
    ElseIf Not StringLen($sData) Then
        Return SetError(-2, 0, 0); <- no data to send
    EndIf
    ;
    Local $nBytesSent = TCPSend($iSocket, $sData)
    Local $nError = @error
    ;
    If $nError Then
        Return SetError($nError, 0, 0)
    Else
        Return SetError(0, 0, $nBytesSent)
    EndIf
EndFunc

You can substitute _WSA_TCPSend(), if you have problems with TCPSend(), since I haven't tested how the native function works with non-blocking sockets.

The WSA_NBTCP UDF was never intended to mix with other types. You either use one or the other, but not a mix of them. Unpredictable results will probably occur.

 

Edited by ripdad

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

Share this post


Link to post
Share on other sites
21 hours ago, ripdad said:

The WSA_NBTCP UDF was never intended to mix with other types. You either use one or the other, but not a mix of them. Unpredictable results will probably occur.

Possibly with another WSA_NBTCP UDF  custom made and optimized to force\make it play along 
or accommodate _WSA_client-server UDFs that can be based on WSA_NBTCP UDF as is

(Not something I'm going to ask anyone to do .. )

I was only curious in asserting the benefits over the native functions if it was going to be an easy and applicable switch over 

Thanks for all the input and follow up calls

Deye

Share this post


Link to post
Share on other sites

It should not be difficult to switch over -- and should be fairly transparent.

As for "asserting the benefits", there are several. I'll list a few the native functions don't have...

1. _WSA_TCPRecv() -- BytesReceived in @extended, the Timeout Feature, and at the moment, proper error returns.
2. _WSA_TCPSend() -- BytesSent in @extended and the Select Timeout, which you can adjust.
3. The UDF can be tweaked how you want - because the source code is available to you for instant access.

And you're welcome. Glad to help whenever I can.


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

Share this post


Link to post
Share on other sites

Hi ripdad !

I'm trying to replace native Autoit tcp functions by yours and I've got a problem.

How do you handle tcpconnect part when the client is trying to connect to a downed server ?

With native function, i'm using this code :

$RecvPacket = TCPRecv($ConnectedSocket, $PacketSize)
If @error Then
    TCPCloseSocket($ConnectedSocket)
    $ConnectedSocket = TCPConnect($server_ip, $port)
    While @error
      _Sleep(2000)
      $ConnectedSocket = TCPConnect($server_ip, $port)
    WEnd
EndIf

But using the same code with _WSA_TCPConnect not reconnects the client if the server goes back online.

EDIT : NVM, I was not using your functions correctly.

Edited by tatane

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  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By TheXman
      Purpose (from Microsoft's website)
      The HTTP Server API enables applications to communicate over HTTP without using Microsoft Internet Information Server (IIS). Applications can register to receive HTTP requests for particular URLs, receive HTTP requests, and send HTTP responses. The HTTP Server API includes SSL support so that applications can exchange data over secure HTTP connections without IIS.
      Description
      There have been several times in the past that I wanted to either retrieve information from one of my PCs or execute commands on one of my PCs, whether it was from across the world or sitting on my couch.  Since AutoIt is one of my favorite tools for automating just about anything on my PC, I looked for ways to make to make it happen.  Setting up a full blown IIS server seemed like overkill so I looked for lighter weight solutions.  I though about creating my own AutoIt UDP or TCP server but that just wasn't robust enough,  Then I found Microsoft's HTTP Server API and it looked very promising.  After doing a little research into the APIs, I found that it was flexible & robust enough to handle just about any of the tasks that I required now and in the future.  So a while back I decided to wrap the API functionality that I needed into an AutoIt UDF file to allow me to easily create the functionality I needed at the time.  It has come in very handy over the years.  Of course it wasn't all wrapped up with a nice little bow like it is now.  That only happened when I decided to share it with anyone else who could use it or learn from it.
      The example file that I included is a very granular example of the steps required to get a lightweight HTTP Server up and listening for GET requests.  The UDF is a wrapper for the Microsoft APIs.  That means to do anything over and above what I show in the example, one would probably have to have at least a general knowledge of APIs or the ability to figure out which APIs/functions to use, what structures and data is needed to be passed to them, and in what order.  However, the UDF gives a very solid foundation on which to build upon.  Of course, if anyone has questions about the UDF or how to implement any particular functionality, I would probably help to the extent that I could or point you in the right direction so that you can figure out how to implement your own solution.
      The APIs included in the UDF are the ones that I needed in the past to do what I needed to do.  If any additional APIs need to be added to the UDF file, please make those suggestions in the related forum topic.
      Being that this is basically an AutoIt wrapper for the Microsoft API functions, there's no need to create AutoIt-specific documentation.  All of the UDF functions, structures, constants, and enumerations are named after their Microsoft API counterparts.  Therefore, you can refer to Microsoft's extensive documentation of their HTTP Server API.  As stated earlier, if there is one or more APIs that you find yourself needing for your particular solution, please suggest it in the related Example Scripts forum topic.
      Related Links
      Microsoft HTTP Server API - Start Page
      Microsoft HTTP Server API - API v2 Reference
      Microsoft HTTP Server API - Programming Model
    • By YogendraAtluri
      Hi, 
      I am new to AutoIT scripting and I am still learning. I am trying to communicate with a Labview application that acts like a server. it basically takes commands from the client. But for some commands, it also send back some data. 
      When i am sending commands from my script, i can see that the labview is getting them. But i am not able to get anything back. I tried different code pieces that are available online in the forum.
      This is the working piece of code which i been using to send data.
      #cs This module is used to establish tcp connection with lab view #ce #include <File.au3> Func SendCmd($cmd) TCPStartup() Local $IpAddress="192.168.10.101" Local $Port="5353" $Labview = TCPConnect($IpAddress,$Port) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ).' & @CRLF) TCPCloseSocket($Labview) TCPShutdown() Exit EndIf TCPSend($Labview, $cmd & @CRLF) TCPCloseSocket($Labview) TCPShutdown() EndFunc SendCmd("wt42d")  
      This is slightly modified code to send and receive data, which is not working. I am not getting any response back
      SendCmd("galil") Func SendCmd($cmd) TCPStartup() Local $IpAddress="192.168.10.101" Local $Port="5353" $Labview = TCPConnect($IpAddress,$Port) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ).' & @CRLF) TCPCloseSocket($Labview) TCPShutdown() Exit EndIf TCPSend($Labview, $cmd & @CRLF) $ip = @IPAddress1 ;create listening socket $Listensocket = TCPListen($ip, $Port) ConsoleWrite("Listening to Socket - " & $Listensocket & @CRLF) If $Listensocket = -1 Then ConsoleWrite("Exiting..." & @CRLF) Exit EndIf ;Accept incoming clients and recieve info While 1 $connectedsocket = TCPAccept($Listensocket) ConsoleWrite("Connecting to Socket - " & $connectedsocket & "Error -" & @error & @CRLF) If $ConnectedSocket >= 0 Then $ip2 = TCPRecv($connectedsocket,1000000) EndIf WEnd TCPCloseSocket($connectedsocket) TCPCloseSocket($Labview) TCPShutdown() EndFunc I am not getting anything back. I am getting the following output in the console
      +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Listening to Socket - 544 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 Connecting to Socket - -1Error -0 its going through that loop forever. i need to force stop it.
      But when i open putty and send the same command, i am getting response right away. 
      Can someone please help me with that.
      Thanks in advance
      Regards
      Yogendra
    • By argumentum
      I can TCP/IP in AutoIt, hence, make a HTTP deamon. Now, how can I HTTPS to use SSL !??
      Well, Apache has this "mod_proxy.so" module that can let me have SSL and what not is in Apache.
      All that is needed is to tell Apache what I wanna do by editing httpd.conf .
      # Implements a proxy/gateway for Apache. # 1. Open /Applications/XAMPP/etc/httpd.conf # 2. Enable the following Modules by removing the # at the front of the line. # - LoadModule rewrite_module modules/mod_rewrite.so # - LoadModule proxy_module modules/mod_proxy.so # - LoadModule proxy_http_module modules/mod_proxy_http.so # # 3. Copy and Paste below to the bottom of httpd.conf # <IfModule mod_proxy.c> ProxyRequests On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyVia Off ProxyPreserveHost Off ProxyPass /home/ http://127.0.0.1:84/home/ ProxyPassReverse /home/ http://127.0.0.1:84/home/ SetEnv proxy-nokeepalive 1 # ..since we are not using "keep-alive", we are using "close" </IfModule> ...et voila  
      I'm using XAMPP ( https://www.apachefriends.org/download.html )
      and this is my solution to avoid coding in PHP, as I feel more comfortable coding in AutoIt.
      A "muli-thread or concurrency" can be done by forking the socket ( https://www.autoitscript.com/forum/topic/199177-fork-udf-ish/ )
      but responses are under 20 ms., so I feel fine with a single thread.
      I modified an example ( attached below ), so can try out the concept.
      PS: I am not an Apache guru. I just discovered this and it opens a world of possibilities. In my case, I'm thinking of an API to query SQLite 
      PS2: I'm not gonna make Poll but do click like if you do  
       
      201673-json-http-post-serverlistener.au3
    • By tarretarretarre
      Autoit-Socket-IO
      Introduction
      Autoit-Socket-IO is a event driven TCP/IP wrapper heavily inspired from Socket.IO with focus on user friendliness and long term sustainability.
      I created this UDF because I was fascinated how Socket.IO made a such scary task "reliable and secure networking" so simple for the developer. So this was my main motivation.
      I constantly want to make this UDF faster and better, so if you have any suggestions. Do not hesitate to make requests!
      Features
      Flexiable and easy to understand API Above avarage documentation "Fully featured" examples Security in form of data encryption and middleware-support Limitations
      Speed. Because I want this UDF to be as flexible and simple as possible. Sometimes speed is sacrificed, but that does not mean i don't try to . It is not possible to emit objects mainly because autoit does not support serialization. Only 1D-arrays can be emitted (2D arrays will probably never be supported) Success story
      Since December 2017-now I have used version 1.5.0 in an production environment for 40+ clients with great success, the only downtime is planned windows updates and power outages.
      Getting started
      Download the script from AutoIt or pull it from the official github repo git@github.com:tarreislam/Autoit-Socket-IO.git and checkout the tag 2.0.0 The documentation is located at Docs\index.html Take a look in the examples/ folder Changelog
      Version 2.0.0 (This update break scripts. Please consult the upgrade.md for guidance)
      All global internal variables has been renamed. Added a bunch of new API methods: _Io_RegisterMiddleware, _Io_whoAmI, _Io_IsClient, _Io_IsServer, _Io_getAllByProperty and _Io_getFirstByProperty and some more. Read more about these in the documentation. _Io_socketGetProperty now has a setter method called _Io_socketSetProperty which can be used to set custom properties. _Io_socketGetProperty now has a third parameter "default" which is used when a property is not found Removed _Io_setEventPostScript and _Io_setEventPretScript in favor of _Io_RegisterMiddleware Improved documentation (It still needs some love though) Improved the verbosity of _Io_DevDebug  
      Newest version (2019-09-29!)
      Autoit-Socket-IO-2.0.0.zip
      Older versions (Not supported anymore)
      Autoit-Socket-IO-1.0.0.zip Autoit-Socket-IO-1.1.0.zip Autoit-Socket-IO-1.3.0.zip Autoit-Socket-IO-1.4.0.zip Autoit-Socket-IO-1.5.0.zip
    • By AoRaToS
      I started working on this program in the summer of 2008 then I stopped cause I faced some problems I couldn't overcome back then. Now that I've practiced more and have become a better scripter/programmer I'm releasing the program to the public to get some opinions. I know it's not a new concept but it's the first program I started besides some small stuff I did just for practice! I won't post the source code yet because it's still under construction, although I'm sure I've posted early stages of the code with bugs in the past in some topic...
      What I wanted was a simple, small, serverless program that would work without installation cause I wanted it for where I work, so I ended up with this!
      I have attached some images of various versions, also visit the forum thread.
      The package includes s!mpL3 LAN Messenger and the full change log.
      Current version 2.9.9.1! [04/07/2019]
      Check the Change Log below!
       
       
      http://www.autoitscript.com/forum/index.php?showtopic=88782
       
       
       
      Read the license before using this software.
       
×
×
  • Create New...