Jump to content
Sign in to follow this  
yhu420

TCP Issues

Recommended Posts

Hello everyone,

I'm trying to create a small program that would allow me to send files across my network, therefore, I copy pasted the code available right here.

I modified the code a little to suit my needs, it is in the spoiler below:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Outfile_x64=server.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#include <Misc.au3>
Global Const $WS_CAPTION = 0x00C00000
Global Const $WS_POPUP = 0x80000000
Global Const $WS_POPUPWINDOW = 0x80880000
Global Const $WS_EX_ACCEPTFILES = 0x00000010
Global Const $TCS_FIXEDWIDTH = 0x00000400
Global Const $PBS_SMOOTH = 1
Global Const $SS_CENTER = 1
Global Const $GUI_EVENT_CLOSE = -3
Global Const $GUI_SHOW = 16
Global Const $GUI_BKCOLOR_TRANSPARENT = -2
Global Const $GUI_DROPACCEPTED = 8
Global Const $ES_NUMBER = 8192

OnAutoItExitRegister("OnAutoItExit")
$GUI = GUICreate("TCP File Transfer - Intended server: " & @IPAddress1, 321, 228, -1, -1, BitOR($WS_POPUPWINDOW, $WS_CAPTION), $WS_EX_ACCEPTFILES)
GUICtrlCreateTab(10, 10, 300, 145, $TCS_FIXEDWIDTH)

GUICtrlCreateTabItem("Receiver")
GUICtrlSetState(-1, $GUI_SHOW)
$Receiver_Destination = GUICtrlCreateInput("", 24, 90, 187, 22)
GUICtrlCreateLabel("Select a destination directory. If one is not selected, it will be set to the desktop.", 24, 45, 272, 40)
GUICtrlSetFont(-1, 10)
$Receiver_Browse = GUICtrlCreateButton("Browse...", 221, 90, 75, 22, 0)
$Receiver_Wait = GUICtrlCreateButton("Wait for File", 24, 121, 272, 22, 0)

GUICtrlCreateTabItem("Sender")
GUICtrlCreateLabel("Select a file to send.", 29, 50, 262, 20)
GUICtrlSetFont(-1, 10)
$Sender_File = GUICtrlCreateInput("", 29, 80, 177, 22)
GUICtrlSetState(-1, $GUI_DROPACCEPTED)
$Sender_Browse = GUICtrlCreateButton("Browse...", 216, 80, 75, 22, 0)
$Sender_Chunk = GUICtrlCreateInput("5", 142, 113, 65, 22, $ES_NUMBER)
GUICtrlCreateLabel("Chunk Size in kb:", 29, 114, 107, 20)
GUICtrlSetFont(-1, 10)
GUICtrlSetLimit(-1, 2, 1)
$Sender_Send = GUICtrlCreateButton("Send", 216, 113, 75, 22, 0)
GUICtrlCreateTabItem("")

$Progress = GUICtrlCreateProgress(10, 192, 300, 25, $PBS_SMOOTH)
$Bytes_Label = GUICtrlCreateLabel("0kb / 0kb", 10, 168, 300, 20)
GUICtrlSetFont(-1, 10)
$Progress_Label = GUICtrlCreateLabel("0%", 10, 196, 300, 24, $SS_CENTER)
GUICtrlSetFont(-1, 12)
GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT)
GUISetState()

TCPStartup()
While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Receiver_Browse
            $Dir = FileSelectFolder("Select a Destination Directory", @HomeDrive)
            If Not @error Then GUICtrlSetData($Receiver_Destination, $Dir)
            GUICtrlSetTip($Dir, GUICtrlRead($Receiver_Destination))
        Case $Receiver_Wait
            Select
                Case GUICtrlRead($Receiver_Destination) = ""
                    GUICtrlSetData($Receiver_Destination, @DesktopDir)
                Case DirGetSize(GUICtrlRead($Receiver_Destination)) = -1
                    GUICtrlSetData($Receiver_Destination, @DesktopDir)
            EndSelect
            _ReceiveFile(GUICtrlRead($Receiver_Destination), 5 * 1024 * 1024) ;file limit of 5 megabytes
            Switch @error
                Case 0
                    MsgBox(262208, "TCP Sender", "Download Complete")
                Case 1
                    MsgBox(16, "WSA:" & @error, "Unable to hook port!")
                Case 2
                    MsgBox(16, "WSA:" & @error, "Lost connection while receiving! Extended: " & @extended)
                Case 3
                    MsgBox(16, "WSA:" & @error, "Lost connection while receiving! Extended: " & @extended)
            EndSwitch
        Case $Sender_Browse
            $File = FileOpenDialog("Select a File To Send", @DesktopDir, "ALL (*.*)", 1 + 2)
            If Not @error Then GUICtrlSetData($Sender_File, $File)
            ;GUICtrlSetTip($Dir, GUICtrlRead($Sender_File))
        Case $Sender_Send
            Select
                Case Not FileExists(GUICtrlRead($Sender_File))
                    MsgBox(262192, "ERROR", "Invalid file!")
                Case GUICtrlRead($Sender_Chunk) > 20
                    MsgBox(262192, "ERROR", "Chunk size specified is too large!")
                Case GUICtrlRead($Sender_Chunk) < 5
                    MsgBox(262192, "ERROR", "Chunk size specified is too small!")
                Case Else
                    _SendFile(GUICtrlRead($Sender_File), GUICtrlRead($Sender_Chunk) * 1024)
                    Switch @error
                        Case 0
                            MsgBox(262208, "TCP Sender", "Upload Complete")
                        Case 1
                            MsgBox(16, "ERROR", "Bad file")
                        Case 2
                            MsgBox(16, "ERROR", "You can't send directories!")
                        Case 3
                            MsgBox(16, "WSA:" & @extended, "Unable to connect to the host!")
                        Case 4
                            MsgBox(16, "WSA:" & @error, "Lost connection while sending! Extended: " & @extended)
                        Case 5
                            MsgBox(16, "ERROR", "That's odd!" & @CRLF & 'I got: "' & @extended & '" from the socket!')
                        Case 6
                            MsgBox(16, "WSA:" & @error, "Lost connection while sending! Extended: " & @extended)
                        Case 7
                            MsgBox(16, "ERROR", "That's odd!" & @CRLF & 'I got: "' & @extended & '" from the socket!')
                    EndSwitch
            EndSelect
    EndSwitch
    Sleep(15)
WEnd

Func _SendFile($File, $MaxLen)
    Local $BytesRead = 0

    $Size = FileGetSize($File)
    If $Size = 0 Then Return SetError(1, 0, -1)

    ;get file name
    $Reg = StringRegExp($File, "(.)+\\((.)+)?", 3)
    ConsoleWrite($Reg & @CRLF)
    Select
        Case Not IsArray($Reg)
            $Name = $Reg
        Case UBound($Reg) < 2
            Return SetError(2, 0, -1)
        Case Else
            $Name = $Reg[1]
    EndSelect
    $IP = InputBox("IP Address", "What is the IP address of the server?", @IPAddress1)

    $Socket = TCPConnect($IP, 8081)
    If @error Then Return SetError(3, @error, -1)

    ;wait until something is sent
    Do
        $Receive = TCPRecv($Socket, 1000)
        ;If @error Then Return SetError(4, 0, -1)
        If @error Then
            ;MsgBox(0, "", "Error: " & @error & " in sending."); --> -1 error
            Return SetError(4, 0, -1)
        EndIf
        Sleep(10)
    Until $Receive <> ""

    If $Receive <> "Sending Data" Then Return SetError(5, $Receive, -1)

    ;Send Name and file size to receiver
    TCPSend($Socket, $Name & ":" & $Size)

    ;Wait for confirmation from receiver
    Do
        $Receive = TCPRecv($Socket, 1000)
        If @error Then SetError(6, 0, -1)
    Until $Receive <> ""

    If $Receive <> "Start Upload" Then SetError(7, $Receive, -1)

    ;open file to read in binary
    $FileHandle = FileOpen($File, 16)

    ;loop until the whole file is received
    While 1
        $Data = FileRead($FileHandle, $MaxLen)
        If @error Then ExitLoop

        $BytesRead += TCPSend($Socket, $Data)

        If GUICtrlRead($Progress) <> Round($BytesRead / $Size * 100) Then
            GUICtrlSetData($Progress, Round($BytesRead / $Size * 100))
            GUICtrlSetData($Bytes_Label, Round($BytesRead / 1024) & " kb / " & Round($Size / 1024) & " kb")
            GUICtrlSetData($Progress_Label, Round($BytesRead / $Size * 100) & "%")
        EndIf
    WEnd
    FileClose($FileHandle)
    TCPCloseSocket($Socket)

    Return SetError(0, 0, 1)
EndFunc   ;==>_SendFile

Func OnAutoItExit()
    TCPShutdown() ; Close the TCP service.
EndFunc   ;==>OnAutoItExit

Func _ReceiveFile($Destination, $MaxLen)

    Local $Return = False, $Bytes = 0

    $Listen = TCPListen(@IPAddress1, 8081)
    If @error Then Return SetError(1, 0, -1)

    ;ToolTip("Listening" & @CRLF & @IPAddress1 & @CRLF & 8081, 0, 0)

    ;wait for sender to connect
    Do
        $Socket = TCPAccept($Listen)
    Until $Socket <> -1

    ;If @error Then MsgBox(0, "", "Bug here")
    ;No bug here

    $Receive = TCPRecv($Socket, $MaxLen)
    ;If @error Then Return SetError(2, 0, -1)
    If @error Then
        ;MsgBox(0, "", "Error " & @error & " in receiving."); --> -1 error
        Return SetError(2, 0, -1)
    EndIf

    TCPSend($Socket, "Sending Data")

    ;get file data
    ;wait for file name and size to be sent
    Do
        $Receive = TCPRecv($Socket, 1000)
        If @error Then Return SetError(3, 0, -1)
        Sleep(5)
    Until $Receive <> ""
    $FileData = StringSplit($Receive, ":", 2)

    $Destination &= "\" & $FileData[0]

    $FileHandle = FileOpen($Destination, 16 + 2 + 8)

    ;initiate download
    TCPSend($Socket, "Start Upload")

    While 1
        $Data = TCPRecv($Socket, $MaxLen, 1) ;receive data in binary
        If @error Then ExitLoop

        $Bytes += BinaryLen($Data) ;count number of bytes sent

        FileWrite($FileHandle, $Data) ;recreate the file sent


        If GUICtrlRead($Progress) <> Round($Bytes / $FileData[1] * 100) Then
            GUICtrlSetData($Progress, Round($Bytes / $FileData[1] * 100))
            GUICtrlSetData($Bytes_Label, Round($Bytes / 1024) & " kb / " & Round($FileData[1] / 1024) & " kb")
            GUICtrlSetData($Progress_Label, Round($Bytes / $FileData[1] * 100) & "%")
        EndIf

    WEnd
    FileClose($FileHandle)
    TCPCloseSocket($Socket)
    TCPCloseSocket($Listen)
    ;ToolTip("")

    Return SetError(0, 0, 1)
EndFunc   ;==>_ReceiveFile

So I ran the program, clicked on "Wait for file" on my main computer, ran it again on my other computer, chose a fie, and I set the IP to the one of my first computer (192.168.x.x).

However, the I only get a loading time, and a WSA error 10060 (Time out).

I double checked with the examples of the official autoit doc, but unfortunately, I have no idea where my mistake is..

Do you guys have any idea?

Thanks ;)

EDIT: removed unnecessary code

Edited by yhu420

Share this post


Link to post
Share on other sites

Yes, the first time I launched this program, it prompted me whether I should allow it or prevent it from using the ports. I clicked "Yes", and it never asked again.

I noticed two other things: I have VirtualBox installed, which makes @IPAddress2 my real IP on the network (I think).

The client/server example given in the TCPRecv doc works just fine. I think I will rather work from this.

Share this post


Link to post
Share on other sites

Just to test if these computers can comunicate to each other, try:

1. Ping from one against another

2. Start a netcat server in one of them (nc -vv -l -p 8081) and try connecting from another (nc -vv 192.168.x.x 8081)


My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

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 tarretarretarre
      Version 2.x.x and 3.x.x has been moved to branch 3.x
      About Autoit-Socket-IO
      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 constantly want to make this UDF faster and better, so if you have any suggestions or questions (beginner and advanced) Do not hesitate to ask them, I will gladly help!
      Key features
      Simple API 99% data-type serialization thanks to Autoit-Serialize Can easily be extended with your own functionality thanks to Autoit-Events "Educational" examples Data encryption thanks to _<Crypt.au3> Limitations
      Speed. This UDF will sacrifice some speed for convenience 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 4.0.0-beta Check out the documentaion Take a look in the examples/ folder Changelog
      To see changes from 3.x.x and 2.x.x please checkout the 3.x branch
      Version 4.0.0-beta (This update break scripts.)
      Code base fully rewritten with Autoit-Events and decoupled to improve code quality and reduce bloat. The new UDF is very different from 3.x.x so please checkout the UPGRADE guide to fully understand all changes Added new documentation documentaion Success stories
      Since December 2017-now I have used version 1.5.0 in an production environment for 150+ clients with great success, the only downtime is planned windows updates and power outages.
       
      Newest version (2020-09-15!)

       
      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
      Autoit-Socket-IO-2.0.0.zip
    • By tarretarretarre
      Version 2.x.x and 3.x.x has been moved to branch 3.x
      About Autoit-Socket-IO
      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 constantly want to make this UDF faster and better, so if you have any suggestions or questions (beginner and advanced) Do not hesitate to ask them, I will gladly help!
      Key features
      Simple API 99% data-type serialization thanks to Autoit-Serialize Can easily be extended with your own functionality thanks to Autoit-Events "Educational" examples Data encryption thanks to _<Crypt.au3> Limitations
      Speed. This UDF will sacrifice some speed for convenience Read more in the official thread
    • 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
×
×
  • Create New...