Jump to content
DrAhmed

Unstable TCP socket connection server keeps disconnecting and connecting all the time

Recommended Posts

DrAhmed

I am working on a code of  Client-Server Connection for a while (Like Teamviewer) , the problem is that the server keeps disconnecting and connecting all the time , In the client i wrote a code to notify me each time server is online , I am getting around 10 notifications each 1 minute from same server :

This is the server code :

TCPStartup()
Local $ConnectedSocket
Local $My_IP = "127.0.0.1"
Local $My_PORT = '5000'
Local $UserID = "MyID"


; Connect
Connect($My_IP, $My_PORT)

While 1

If TCPConnect($My_IP, $My_PORT) <> -1 Then
        $recv = TCPRecv($ConnectedSocket, 2048)
        $RecvSpl = StringSplit($recv, "|")


         Switch $RecvSpl[1]
            Case "order1"
          ; Do something
          MsgBox(64,"Success","You are now connected to the client")
          AddLogToClinet("My server is Online", $UserID, "Green")

         EndSwitch
Else
        $Connected = False
        Connect($IP, $My_PORT)
EndIf

    Sleep(100)
WEnd

; Connect To the Client
Func Connect($IP, $Port)
    Local $iConnectAttempts = 0
    TCPStartup()
    Do
        $ConnectedSocket = TCPConnect($IP, $Port)
        Sleep(1000)
    Until ($ConnectedSocket > 0 or $iConnectAttempts > 10)
    
            Return SetError(@error, 0, $ConnectedSocket)
 EndFunc   ;==>Connect

 ; Send To Client
Func SockSend($Cmd, $Text)
TCPSend($ConnectedSocket, $Cmd & $SockSpl & $Text & $PocketSpl, 4)
EndFunc   ;==>SockSend

; Add Log To Server
Func AddLogToClinet($Data, $UserID, $Color)
SockSend("AddLog", $Data & $SockSpl & $UserID & $SockSpl & $Color)
EndFunc   ;==>AddLogToClinet

At first the Connection function was : 

; Connect To the Client ( Old )
Func Connect($IP, $Port)
    TCPStartup()
    $ConnectedSocket = TCPConnect($IP, $Port)

    If @error Then
        Connect($IP, $My_PORT) ; <<<<<<<<<<<<<<< This was the causing recursion error
    Else
        $Connected = True
    EndIf
 EndFunc   ;==>Connect

It was working  good , except I had 'recursion level has been exceeded  error (old one)

WRisIQI.jpg

 I've tried  increasing the delay for current code by :

Opt("TCPTimeout", 5000)

However it did not help yet what do you suggest to me ?

 

Edited by DrAhmed

Share this post


Link to post
Share on other sites
willichan

Several times per second, you are opening a connection to the server, and not closing it.  If you are not communicating, or needing to keep the connection open, be sure to close it when done with it.  If you open too many connections, you will eventually be dropped.

Maybe try putting a TCPCloseSocket() statement after your TCPRecv() statement.

Share this post


Link to post
Share on other sites
DrAhmed
11 hours ago, willichan said:

Several times per second, you are opening a connection to the server, and not closing it.  If you are not communicating, or needing to keep the connection open, be sure to close it when done with it.  If you open too many connections, you will eventually be dropped.

Maybe try putting a TCPCloseSocket() statement after your TCPRecv() statement.

But, like you said I need to keep the connection open all the time, to make the server receive orders any time when it's online .

Share this post


Link to post
Share on other sites
DrAhmed

any help is welcomed even if it is another method for connection ^_^

Share this post


Link to post
Share on other sites
willichan

I was mainly suggesting that you not repeatedly create socket connections several times per second and keep them open.

Make a connection, do what you need to do (looks like all you are doing is checking to see if the connection succeeded), then disconnect.  If you are not actually transferring data across the connection, then you don't need to keep it open.  If you are transferring data, then suspend your loop since you do not need to be opening new connections.  The reason your script is reporting that you are dropping connectivity is because you are reaching the limit on open sockets.  You actually have several successfully open sockets, but since there are no more sockets available, TCPConnect() fails, and your script interprets that as a loss of connection to the server.  When your script re-issues the TCPStartup(), you are then killing all of those successful socket connections, and starting over.  Again, you have most likely not really lost connection to the server, but you are rather causing the connection to fail after falsely identifying the connection as lost.

Hopefully, that explanation is a little more helpful.  Good luck!

 

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

  • Similar Content

    • Spartan117
      By Spartan117
      Hi everyone,
      I wonder if there is a cloud service that can offer a physical server so that AutoIT can turn as it is in a physical machine.
      Thank you
    • ripdad
      By ripdad
      I have had several people ask for this, so I decided to work the algorithm for it and this is the result.
      What is it?
      A Gateway Proxy Sends and Receives Data Unmodified.
      https://en.wikipedia.org/wiki/Proxy_server
      What is it used for?
      You can use it as a gateway, relay or router between two known static IP addresses.
      More information is in the header of the script.
      Download: LocalGatewayProxy.au3
      You will need WSA_NBTCP.au3 from here:
      https://www.autoitscript.com/forum/topic/191954-wsa_nbtcp-v100-udf/
      If you have any questions or problems, let me know.
       
    • ripdad
      By ripdad

      This script is based on algorithm code from EnrMa.
      Updated: January 22, 2018
      Made improvements. Changes are in the script header.
      Known Issues: AutoIt x64 does not work properly with this script.
      Download: LocalProxyServer_v1.00.zip
       
    • ripdad
      By ripdad
      WSA_NBTCP.au3  (Windows Sockets API - Non-Blocking Transmission Control Protocol)
      Version: 1.00
      Type: UDF
      This is an accumulation of WSA code from many sources and modified to suit myself.
      These functions have been thoroughly tested using a Local Proxy Server, which
      is about the most strenuous test you can use.
      Includes my rendition of how a TCPRecv Timeout should work. Also includes a
      timewait/timeout using Select for TCP Send, which works great for that function.
      You will need a loop to use _WSA_TCPRecv(). An example will be forthcoming in a second post.
      Functions:
      #CURRENT_USER_FUNCTIONS
      _WSA_Cleanup
      _WSA_FormatMessage
      _WSA_GetLastError
      _WSA_TCPAccept
      _WSA_TCPCloseSocket
      _WSA_TCPConnect
      _WSA_TCPListen
      _WSA_TCPRecv
      _WSA_TCPSend

      #INTERNAL_FUNCTIONS
      __TimeoutManager
      __TimeoutReset

      #EXTRA_FUNCTIONS
      _WSA_GetAddrInfo
      _WSA_GetHostByAddr
      _WSAAsyncGetHostByName
      _WSAAsyncGetHostByName_Callback
      _WSA_GetNameInfo
       
      Requirements:
      - AutoIt Versions: 3.3.8.1 thru 3.3.15.0 (32Bit only).
      - TCPStartup() at beginning of script on startup.
      - TCPShutDown() and _WSA_Cleanup() on exit.
      Download UDF: WSA_NBTCP.au3
       
    • tarretarretarre
      By tarretarretarre
      AutoIt-SocketIo
      Yep yep, this is pretty much an attempt to port the existing project's concept https://socket.io/ to AutoIt's Codebase. So i will not go in to so much detail.
      This is how the communication is done http://i.imgur.com/0mMfsBD.png Each client is isolated to the server http://i.imgur.com/rVO2LFb.png Features
      Easy API VarType Translation (Example: If the server sends an int, the client will receive an int and vice versa) Fully featured examples Data encryption (Using Autoit's UDF Crypt.au3) Limitations / Drawbacks
      It is not possible to Broadcast/Emit objects Only 1D-arrays are allowed to be Broadcasted/Emitted (2D arrays will probably never be supported) Changelog
      Version 1.5.0 (This update DOES NOT break scripts)
      Added AutoIt like docs under Docs\. The docs are generated so its a 1 to 1 reflection of the UDF headers. Print of documentation Added a production ready server example. Added a new method: _Io_DevDebug which will display useful information when debugging. Added a new method: _Io_SetMaxRecvPackageSize which defaults to whatever _Io_setRecvPackageSize is set to. Added a new method: _Io_setOnPrefix which defaults to _On_ Added a new default client & server event called flood. Flood occurs when exceeding the $__g_io_nMaxPacketSize. $__g_io_nMaxPacketSize is set by _Io_SetMaxRecvPackageSize Fixed the 16 parameter limit when sending data with _Io_Emit, _Io_Broadcast, _Io_BroadcastToAll and _Io_BroadcastToRoom. This works on the same premise that AutoIt's Call Does Fixed a TRUNCATION problem when receiving packages which could cause crashes! Fixed a programming error which caused $__g_ionPacketSize to reset to default 4096 if _Io_Connect or _Io_listenwere called after _Io_setRecvPackageSize Fixed _Io_setEventPreScript and _Io_setEventPostScript They didnt work. Lol. Changed how events are fired so the client cannot crash the server by sending the wrong number of parameters (This also allows for optional parameters on callbacks) Changed _Io_On. The second parameter $fCallback can now be set to null. Doing this, the function assumes that the callback is: _On_<eventName>.  
      Changelog History
      Api methods
      Please see the docs provided
      Default events
      Server events
      connection Client events
      banned Server and Client events
      disconnect flood View source on github
       
      Autoit-Socket-IO-1.0.0.zip (OLD!)
      Autoit-Socket-IO-1.1.0.zip (OLD)
      Autoit-Socket-IO-1.3.0.zip (OLD)
      Autoit-Socket-IO-1.4.0.zip (OLD)
      Autoit-Socket-IO-1.5.0.zip (NEWEST 2017-12-20)
×