Jump to content

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 ****
#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_DROPACCEPTED = 8
Global Const $ES_NUMBER = 8192

$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)

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)

GUICtrlCreateLabel("Select a file to send.", 29, 50, 262, 20)
GUICtrlSetFont(-1, 10)
$Sender_File = GUICtrlCreateInput("", 29, 80, 177, 22)
$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)

$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)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
        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
                Case GUICtrlRead($Receiver_Destination) = ""
                    GUICtrlSetData($Receiver_Destination, @DesktopDir)
                Case DirGetSize(GUICtrlRead($Receiver_Destination)) = -1
                    GUICtrlSetData($Receiver_Destination, @DesktopDir)
            _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)
        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
                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!')

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)
        Case Not IsArray($Reg)
            $Name = $Reg
        Case UBound($Reg) < 2
            Return SetError(2, 0, -1)
        Case Else
            $Name = $Reg[1]
    $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
        $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)
    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
        $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) & "%")

    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
        $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)

    TCPSend($Socket, "Sending Data")

    ;get file data
    ;wait for file name and size to be sent
        $Receive = TCPRecv($Socket, 1000)
        If @error Then Return SetError(3, 0, -1)
    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) & "%")


    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


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

  • Similar Content

    • By HansHenrik
      edit: this is probably in the wrong place, can a moderator move it to wherever it belongs?

      is there any way to completely disable TCPTimeout and make TCPRecv() wait indefinitely? maybe setting it to 0 or -1 or something? 
      the docs doesn't seem to mention any way to disable it

      - the underlying C code would set SO_RCVTIMEO to 0 , aka

      DWORD timeout=0;
      setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
    • 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.
      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:
      If you have any questions or problems, let me know.
    • 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
    • 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.


      - AutoIt Versions: thru (32Bit only).
      - TCPStartup() at beginning of script on startup.
      - TCPShutDown() and _WSA_Cleanup() on exit.
      Download UDF: WSA_NBTCP.au3
    • By tarretarretarre
      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)
  • Create New...