Search the Community

Showing results for tags 'tcp'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • General
    • Announcements and Site News
    • Chat
    • Administration
  • AutoIt v3
    • AutoIt Help and Support
    • AutoIt Technical Discussion
    • AutoIt Example Scripts
  • Scripting and Development
    • Developer General Discussion
    • Language Specific Discussion
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • AutoIt Team
    • Beta
    • MVP
  • AutoIt
    • Automation
    • Databases and web connections
    • Data compression
    • Encryption and hash
    • Games
    • GUI Additions
    • Hardware
    • Information gathering
    • Internet protocol suite
    • Maths
    • Media
    • PDF
    • Security
    • Social Media and other Website API
    • Windows
  • Scripting and Development
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • Forum
  • AutoIt

Calendars

  • Community Calendar

Found 46 results

  1. 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 Every Broadcast/Emit is limited to a maximum of 16 parameters Every Callback Function has to have the same number of parameters as the Broadcasted/Emited event 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.1.0 (This update DOES NOT break scripts) Fixed bug when Emitting / Broadcasting without any parameters causing a $fCallback crash Optimized Package-handling once again. Added 1D-Array support (Endless nestning). Added Subscriptions (See _Io_Subscribe _Io_Unsubscribe and _Io_BroadcastToRoom). Added new example for subscriptions (Be sure to use different room names when joining with clients) Added Unit testing (See Tests\Runner.au3 and Tests\Tests.au3, to run tests you need a udf found here: https://github.com/tarreislam/Autoit-Unit-Tester) Version 1.0.0 (This update DOES NOT break scripts) Added data encryption (Using Autoit's UDF Crypt.au3) See more at _Io_EnableEncryption Added new method _Io_Disconnect which can be used with both servers and clients Improved package-handling to increase performance Increased the limit of Broadcasted/Emit parameters from 10 to 16 Api methods Server methods _Io_Listen($iPort, $iAddress = @IPAddress1, $iMaxPendingConnections = Default, $iMaxDeadSocketsBeforeTidy = 1000) _Io_Subscribe(ByRef $socket, $sRoomName) _Io_Unsubscribe(ByRef $socket, $sRoomName = null) _Io_Broadcast(ByRef $socket, $sEventName, $p1, $p2, ...$p16) _Io_BroadcastToAll(ByRef $socket, $sEventName, $p1, $p2, ...$p16) _Io_BroadcastToRoom(ByRef $socket, $sDesiredRoomName, $sEventName, $p1, $p2, ...$p16) _Io_socketGetProperty(ByRef $socket, $sProp = Default) _Io_getSocketsCount() _Io_getDeadSocketCount() Client methods _Io_Connect($iAddress, $iPort, $bAutoReconnect = False) _Io_Reconnect(ByRef $socket) Server and Client methods _Io_getVer() _Io_On(Const $sEventName, Const $fCallback) _Io_Emit(ByRef $socket, $sEventName, $p1, $p2, ...$p16) _Io_Loop(ByRef $socket) _Io_LoopFacade() _Io_EnableEncryption($sFileOrKey, $CryptAlgId = $CALG_AES_256) _Io_Disconnect() Default events Server events connection Server and Client events disconnect View source on github Autoit-Socket-IO-1.0.0.zip (OLD!) Autoit-Socket-IO-1.1.0.zip
  2. i am trying to figure out how a server can connect to a client Over the internet. In this is script. The client connects to the server on the same machine (localhost) and executes the commands from the client. How can I change that instead communicating over localhost to communicate over the internet with tcp ipaddress and a port. What i actually need help of is 1. The server will open a port and listen to communication from a No-ip address 2. I input the no-ip address and correct port in the client side, and when i click on connect, it connects to the server if its online This is the client #include <GuiConstantsEx.au3> THIS IS THE CLIENT #include <NamedPipes.au3> #include <StaticConstants.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> ; =============================================================================================================================== ; Description ...: This is the client side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $BUFSIZE = 4096 Global Const $DEFCMD = "cmd.exe /c dir c:\" Global Const $PIPE_NAME = "\\$\\pipe\\AutoIt3" Global Const $ERROR_MORE_DATA = 234 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_idEdit, $g_idMemo, $g_idSend, $g_idServer, $g_hPipe ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the client ; =============================================================================================================================== Func CreateGUI() Local $hGUI = GUICreate("FarC0nn3c7", 500, 400, -1, -1, $WS_SIZEBOX) GUICtrlCreateLabel("Server:", 2, 14, 52, 20, $SS_RIGHT) $g_idServer = GUICtrlCreateEdit("<local>", 56, 10, 200, 20, $SS_LEFT) GUICtrlCreateLabel("Command:", 2, 36, 52, 20, $SS_RIGHT) $g_idEdit = GUICtrlCreateEdit($DEFCMD, 56, 32, 370, 20, $SS_LEFT) $g_idSend = GUICtrlCreateButton("Pawn Dem", 430, 32, 60, 20) $g_idMemo = GUICtrlCreateEdit("", 0, 62, _WinAPI_GetClientWidth($hGUI), 332) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogError ; =============================================================================================================================== ; Logs a message to the display ; =============================================================================================================================== Func LogMsg($sMessage) GUICtrlSetData($g_idMemo, GUICtrlRead($g_idMemo) & $sMessage & @CRLF) EndFunc ;==>LogMsg ; =============================================================================================================================== ; MsgLoop ; =============================================================================================================================== Func MsgLoop() While True Switch GUIGetMsg() Case $g_idSend SendCmd() Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd EndFunc ;==>MsgLoop ; =============================================================================================================================== ; This function opens a pipe to the server ; =============================================================================================================================== Func OpenPipe() Local $sName, $sPipe ; Get pipe handle $sName = GUICtrlRead($g_idServer) If $sName = "<local>" Then $sName = "." $sPipe = StringReplace($PIPE_NAME, "$", $sName) $g_hPipe = _WinAPI_CreateFile($sPipe, 2, 6) If $g_hPipe <> -1 Then Return True LogError("OpenPipe failed") Return False EndFunc ;==>OpenPipe ; =============================================================================================================================== ; This function reads a message from the pipe ; =============================================================================================================================== Func ReadMsg() Local $bSuccess, $iRead, $pBuffer, $tBuffer $tBuffer = DllStructCreate("char Text[4096]") $pBuffer = DllStructGetPtr($tBuffer) GUICtrlSetData($g_idMemo, "") While 1 $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, 0) If $iRead = 0 Then ExitLoop If Not $bSuccess Or (_WinAPI_GetLastError() = $ERROR_MORE_DATA) Then ExitLoop GUICtrlSetData($g_idMemo, StringLeft(DllStructGetData($tBuffer, "Text"), $iRead), 1) WEnd EndFunc ;==>ReadMsg ; =============================================================================================================================== ; This function sends a command to the server ; =============================================================================================================================== Func SendCmd() If OpenPipe() Then SetReadMode() WriteMsg(GUICtrlRead($g_idEdit)) ReadMsg() _WinAPI_CloseHandle($g_hPipe) EndIf EndFunc ;==>SendCmd ; =============================================================================================================================== ; This function sets the pipe read mode ; =============================================================================================================================== Func SetReadMode() If Not _NamedPipes_SetNamedPipeHandleState($g_hPipe, 1, 0, 0, 0) Then LogError("SetReadMode: _NamedPipes_SetNamedPipeHandleState failed") EndIf EndFunc ;==>SetReadMode ; =============================================================================================================================== ; This function writes a message to the pipe ; =============================================================================================================================== Func WriteMsg($sMessage) Local $iWritten, $iBuffer, $pBuffer, $tBuffer $iBuffer = StringLen($sMessage) + 1 $tBuffer = DllStructCreate("char Text[" & $iBuffer & "]") $pBuffer = DllStructGetPtr($tBuffer) DllStructSetData($tBuffer, "Text", $sMessage) If Not _WinAPI_WriteFile($g_hPipe, $pBuffer, $iBuffer, $iWritten, 0) Then LogError("WriteMsg: _WinAPI_WriteFile failed") EndIf EndFunc ;==>WriteMsg And this is the server #include <GuiConstantsEx.au3> #include <NamedPipes.au3> #include <WinAPI.au3> #include <WindowsConstants.au3> #NoTrayIcon ; =============================================================================================================================== ; Description ...: This is the server side of the pipe demo ; Author ........: Paul Campbell (PaulIA) ; Notes .........: ; =============================================================================================================================== ; =============================================================================================================================== ; Global constants ; =============================================================================================================================== Global Const $DEBUGGING = False Global Const $BUFSIZE = 4096 Global Const $PIPE_NAME = "\\.\\pipe\\AutoIt3" Global Const $TIMEOUT = 5000 Global Const $WAIT_TIMEOUT = 258 Global Const $ERROR_IO_PENDING = 997 Global Const $ERROR_PIPE_CONNECTED = 535 ; =============================================================================================================================== ; Global variables ; =============================================================================================================================== Global $g_hEvent, $g_idMemo, $g_pOverlap, $g_tOverlap, $g_hPipe, $g_hReadPipe, $g_iState, $g_iToWrite ; =============================================================================================================================== ; Main ; =============================================================================================================================== CreateGUI() InitPipe() MsgLoop() ; =============================================================================================================================== ; Creates a GUI for the server ; =============================================================================================================================== Func CreateGUI() Local $hGUI $hGUI = GUICreate("Pipe Server", 500, 400, -1, -1, $WS_SIZEBOX) $g_idMemo = GUICtrlCreateEdit("", 0, 0, _WinAPI_GetClientWidth($hGUI), _WinAPI_GetClientHeight($hGUI)) GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New") GUISetState() EndFunc ;==>CreateGUI ; =============================================================================================================================== ; This function creates an instance of a named pipe ; =============================================================================================================================== Func InitPipe() ; Create an event object for the instance $g_tOverlap = DllStructCreate($tagOVERLAPPED) $g_pOverlap = DllStructGetPtr($g_tOverlap) $g_hEvent = _WinAPI_CreateEvent() If $g_hEvent = 0 Then LogError("InitPipe ..........: API_CreateEvent failed") Return EndIf DllStructSetData($g_tOverlap, "hEvent", $g_hEvent) ; Create a named pipe $g_hPipe = _NamedPipes_CreateNamedPipe($PIPE_NAME, _ ; Pipe name 2, _ ; The pipe is bi-directional 2, _ ; Overlapped mode is enabled 0, _ ; No security ACL flags 1, _ ; Data is written to the pipe as a stream of messages 1, _ ; Data is read from the pipe as a stream of messages 0, _ ; Blocking mode is enabled 1, _ ; Maximum number of instances $BUFSIZE, _ ; Output buffer size $BUFSIZE, _ ; Input buffer size $TIMEOUT, _ ; Client time out 0) ; Default security attributes If $g_hPipe = -1 Then LogError("InitPipe ..........: _NamedPipes_CreateNamedPipe failed") Else ; Connect pipe instance to client ConnectClient() EndIf EndFunc ;==>InitPipe ; =============================================================================================================================== ; This function loops waiting for a connection event or the GUI to close ; =============================================================================================================================== Func MsgLoop() Local $iEvent Do $iEvent = _WinAPI_WaitForSingleObject($g_hEvent, 0) If $iEvent < 0 Then LogError("MsgLoop ...........: _WinAPI_WaitForSingleObject failed") Exit EndIf If $iEvent = $WAIT_TIMEOUT Then ContinueLoop Debug("MsgLoop ...........: Instance signaled") Switch $g_iState Case 0 CheckConnect() Case 1 ReadRequest() Case 2 CheckPending() Case 3 RelayOutput() EndSwitch Until GUIGetMsg() = $GUI_EVENT_CLOSE EndFunc ;==>MsgLoop ; =============================================================================================================================== ; Checks to see if the pending client connection has finished ; =============================================================================================================================== Func CheckConnect() Local $iBytes ; Was the operation successful? If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iBytes, False) Then LogError("CheckConnect ......: Connection failed") ReconnectClient() Else $g_iState = 1 EndIf EndFunc ;==>CheckConnect ; =============================================================================================================================== ; This function reads a request message from the client ; =============================================================================================================================== Func ReadRequest() Local $pBuffer, $tBuffer, $iRead, $bSuccess $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If $bSuccess And ($iRead <> 0) Then ; The read operation completed successfully Debug("ReadRequest .......: Read success") Else ; Wait for read Buffer to complete If Not _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iRead, True) Then LogError("ReadRequest .......: _WinAPI_GetOverlappedResult failed") ReconnectClient() Return Else ; Read the command from the pipe $bSuccess = _WinAPI_ReadFile($g_hPipe, $pBuffer, $BUFSIZE, $iRead, $g_pOverlap) If Not $bSuccess Or ($iRead = 0) Then LogError("ReadRequest .......: _WinAPI_ReadFile failed") ReconnectClient() Return EndIf EndIf EndIf ; Execute the console command If Not ExecuteCmd(DllStructGetData($tBuffer, "Text")) Then ReconnectClient() Return EndIf ; Relay console output back to the client $g_iState = 3 EndFunc ;==>ReadRequest ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func CheckPending() Local $bSuccess, $iWritten $bSuccess = _WinAPI_GetOverlappedResult($g_hPipe, $g_pOverlap, $iWritten, False) If Not $bSuccess Or ($iWritten <> $g_iToWrite) Then Debug("CheckPending ......: Write reconnecting") ReconnectClient() Else Debug("CheckPending ......: Write complete") $g_iState = 3 EndIf EndFunc ;==>CheckPending ; =============================================================================================================================== ; This function relays the console output back to the client ; =============================================================================================================================== Func RelayOutput() Local $pBuffer, $tBuffer, $sLine, $iRead, $bSuccess, $iWritten $tBuffer = DllStructCreate("char Text[" & $BUFSIZE & "]") $pBuffer = DllStructGetPtr($tBuffer) ; Read data from console pipe _WinAPI_ReadFile($g_hReadPipe, $pBuffer, $BUFSIZE, $iRead) If $iRead = 0 Then LogMsg("RelayOutput .......: Write done") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_FlushFileBuffers($g_hPipe) ReconnectClient() Return EndIf ; Get the data and strip out the extra carriage returns $sLine = StringLeft(DllStructGetData($tBuffer, "Text"), $iRead) $sLine = StringReplace($sLine, @CR & @CR, @CR) $g_iToWrite = StringLen($sLine) DllStructSetData($tBuffer, "Text", $sLine) ; Relay the data back to the client $bSuccess = _WinAPI_WriteFile($g_hPipe, $pBuffer, $g_iToWrite, $iWritten, $g_pOverlap) If $bSuccess And ($iWritten = $g_iToWrite) Then Debug("RelayOutput .......: Write success") Else If Not $bSuccess And (_WinAPI_GetLastError() = $ERROR_IO_PENDING) Then Debug("RelayOutput .......: Write pending") $g_iState = 2 Else ; An error occurred, disconnect from the client LogError("RelayOutput .......: Write failed") ReconnectClient() EndIf EndIf EndFunc ;==>RelayOutput ; =============================================================================================================================== ; This function is called to start an overlapped connection operation ; =============================================================================================================================== Func ConnectClient() $g_iState = 0 ; Start an overlapped connection If _NamedPipes_ConnectNamedPipe($g_hPipe, $g_pOverlap) Then LogError("ConnectClient .....: ConnectNamedPipe 1 failed") Else Switch @error ; The overlapped connection is in progress Case $ERROR_IO_PENDING Debug("ConnectClient .....: Pending") ; Client is already connected, so signal an event Case $ERROR_PIPE_CONNECTED LogMsg("ConnectClient .....: Connected") $g_iState = 1 If Not _WinAPI_SetEvent(DllStructGetData($g_tOverlap, "hEvent")) Then LogError("ConnectClient .....: SetEvent failed") EndIf ; Error occurred during the connection event Case Else LogError("ConnectClient .....: ConnectNamedPipe 2 failed") EndSwitch EndIf EndFunc ;==>ConnectClient ; =============================================================================================================================== ; Dumps debug information to the screen ; =============================================================================================================================== Func Debug($sMessage) If $DEBUGGING Then LogMsg($sMessage) EndFunc ;==>Debug ; =============================================================================================================================== ; Executes a command and returns the results ; =============================================================================================================================== Func ExecuteCmd($sCmd) Local $tProcess, $tSecurity, $tStartup, $hWritePipe ; Set up security attributes $tSecurity = DllStructCreate($tagSECURITY_ATTRIBUTES) DllStructSetData($tSecurity, "Length", DllStructGetSize($tSecurity)) DllStructSetData($tSecurity, "InheritHandle", True) ; Create a pipe for the child process's STDOUT If Not _NamedPipes_CreatePipe($g_hReadPipe, $hWritePipe, $tSecurity) Then LogError("ExecuteCmd ........: _NamedPipes_CreatePipe failed") Return False EndIf ; Create child process $tProcess = DllStructCreate($tagPROCESS_INFORMATION) $tStartup = DllStructCreate($tagSTARTUPINFO) DllStructSetData($tStartup, "Size", DllStructGetSize($tStartup)) DllStructSetData($tStartup, "Flags", BitOR($STARTF_USESTDHANDLES, $STARTF_USESHOWWINDOW)) DllStructSetData($tStartup, "StdOutput", $hWritePipe) DllStructSetData($tStartup, "StdError", $hWritePipe) If Not _WinAPI_CreateProcess("", $sCmd, 0, 0, True, 0, 0, "", DllStructGetPtr($tStartup), DllStructGetPtr($tProcess)) Then LogError("ExecuteCmd ........: _WinAPI_CreateProcess failed") _WinAPI_CloseHandle($g_hReadPipe) _WinAPI_CloseHandle($hWritePipe) Return False EndIf _WinAPI_CloseHandle(DllStructGetData($tProcess, "hProcess")) _WinAPI_CloseHandle(DllStructGetData($tProcess, "hThread")) ; Close the write end of the pipe so that we can read from the read end _WinAPI_CloseHandle($hWritePipe) LogMsg("ExecuteCommand ....: " & $sCmd) Return True EndFunc ;==>ExecuteCmd ; =============================================================================================================================== ; Logs an error message to the display ; =============================================================================================================================== Func LogError($sMessage) $sMessage &= " (" & _WinAPI_GetLastErrorMessage() & ")" ConsoleWrite($sMessage & @LF) EndFunc ;==>LogError ; =============================================================================================================================== ; This function is called when an error occurs or when the client closes its handle to the pipe ; =============================================================================================================================== Func ReconnectClient() ; Disconnect the pipe instance If Not _NamedPipes_DisconnectNamedPipe($g_hPipe) Then LogError("ReconnectClient ...: DisonnectNamedPipe failed") Return EndIf ; Connect to a new client ConnectClient() EndFunc ;==>ReconnectClient
  3. Use: Server Script: #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiEdit.au3> #include <GuiStatusBar.au3> #include <MsgBoxConstants.au3> #include <ScrollBarsConstants.au3> #include <WindowsConstants.au3> #include "TCP.au3" OnAutoItExitRegister("_OnExit") Func _OnExit() TCPShutdown() Exit EndFunc ;==>_OnExit #Region Global $hGUI = GUICreate("TCP AutoIT Server", 620, 400, -1, -1, -1, BitOR($WS_EX_ACCEPTFILES, $WS_EX_TOPMOST, $WS_EX_WINDOWEDGE)) Global $sMode = GUICtrlCreateRadio("Server Mode", 16, 8, 97, 17) GUICtrlSetState(-1, $GUI_CHECKED) Global $sGlobalIP = GUICtrlCreateInput("", 170, 8, 120, 21, $ES_READONLY) Global $sServerIP = GUICtrlCreateInput(@IPAddress1, 300, 8, 120, 21, $ES_READONLY) Global $sServerPORT = GUICtrlCreateInput("8888", 425, 8, 39, 21) GUICtrlCreateLabel("IP Server:", 120, 10, 51, 17) Global $bStartServer = GUICtrlCreateButton("Start Server", 512, 6, 89, 33) Global $gMessenger = GUICtrlCreateGroup("Text to Send", 8, 64, 601, 129) Global $tMessenger = GUICtrlCreateEdit("", 15, 85, 489, 97, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "[START]kYtkjq1VuPTdNQtNlLuzUcEA56F4AaxlrhPZ3FSMd9Svss6Fflt0au6GMqMukNudNX02q7VqFVqJaaD0m5GG7hkGhg6TvblZDCZJ2YZNS1lj4t0hSmBly0nMBQYPDc3XTCUD3o4hZnROywXgaw713XHEeiuiXvu6UVXkVvlSdSlox8OkgEu0pk9zKYQJM0nfiiEaCbo4Rp6qKdDsVCtuDgQSmgsXbI5ZIV2kq59AGkX52Zy6OvH2gRuMZeW3ub0aFr9r2c2XpcNOc1FPWcMfHsk77fk8GkYrtLTAYhFt2kzKLS0KKUiVaymVXMcgGhIpeAGfGLt9RSnfgBFMxUzLWMr031ts48toWug85ktsJmdfN9uqHUNGkIEY2pOFNN88PuAqqmoaSit3TvHZgyai7v1XubxaS4G2pK5hB2uhC0rljehCjMo5TRNiOdXvrLELgTT2ema8FbPZoNT4Vs3nb6dYTok7wloUbpK6ggWkHfjG6sAQJItNYPhRdVcB2YqnBbT8hreFoQXy2YAtbtLmRWTbNFvxyiSdn0yK92b4VJT4hIa5UjRkkQ43qwZBIpw5cfhXRXUm7sH6UNiTnLSC4jtFaphrXNSjVsaphMjVi573JjWCIBzTsjxW4PZe7doa7fgilh1gN9CQySFsSzhxGbGMWRqh8wuAEih7CogXIs7YaTq1NQpjLTkTAmcL0HPVYToWnR6D1xyFVUa3hZ8JvUF5bLel84Dljn57NO0ou60O2D6akQ6FuzOnO4cjyLGjvFamVHCan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ton("SEND", 511, 83, 89, 105) GUICtrlCreateGroup("", -99, -99, 1, 1) GUICtrlCreateLabel("File To Send:", 16, 200, 80, 17) Global $sPathFileSend = GUICtrlCreateInput(@TempDir & "\XXX.jpg", 104, 200, 361, 21) Global $bSelectFile = GUICtrlCreateButton(".!.", 472, 200, 35, 25) GUICtrlCreateLabel("Path To Save:", 16, 230, 80, 17) Global $sPathFileSave = GUICtrlCreateInput(@DesktopDir, 104, 230, 361, 21) Global $bSelectDir = GUICtrlCreateButton("...", 472, 230, 35, 25) Global $bSendFile = GUICtrlCreateButton("Send File", 512, 195, 89, 60) ;~ Global $tStatus = GUICtrlCreateLabel("", 16, 45, 580, 17) Global $tStatus = GUICtrlCreateLabel("List Client:", 36, 45, 60, 17) Global $listClient = GUICtrlCreateCombo("", 100, 45, 500, 17) Global $gReceived = GUICtrlCreateGroup("Received", 8, 266, 601, 129) Global $cDataReceived = GUICtrlCreateEdit("", 16, 282, 585, 105, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #EndRegion Global $hClient, $xSocket, $xServerIP, $xServerPORT, $xPathFileSend, $xPathFileSave, $xGlobalIP = GetIP() GUICtrlSetData($sGlobalIP, $xGlobalIP) _WriteLog("Server IP WAN: " & $xGlobalIP) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $bStartServer _WriteLog("SERVER: Starting up server...") $xServerIP = GUICtrlRead($sServerIP) $xServerPORT = GUICtrlRead($sServerPORT) _WriteLog("Server IP: " & $xServerIP) _WriteLog("Server Port: " & $xServerPORT) $hServer = _TCP_Server_Create($xServerPORT, "0.0.0.0") _TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient") _TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect") _TCP_RegisterEvent($hServer, $TCP_RECEIVE, "Recieved") _WriteLog( "SERVER: Started") GUICtrlSetData($bStartServer, "Running") GUICtrlSetState($bStartServer, $GUI_DISABLE) Case $bSendFile ConsoleWrite("Send File Pressed!" & @CRLF) Case $bSendMes Local $sClient = GUICtrlRead($listClient) $xMessenger = GUICtrlRead($tMessenger) _TCP_Send($sClient, $xMessenger) ConsoleWrite("Send Messenger Pressed!" & @CRLF) Case $bSelectFile $xPathFileSend = FileOpenDialog("Select file to send:", @DesktopDir, "All (*.*)", 3, "", $hGUI) If Not @error Then GUICtrlSetData($sPathFileSend, $xPathFileSend) Case $bSelectDir $xPathFileSave = FileSelectFolder("Select local to save file received:", @DesktopDir, 0, @ScriptDir, $hGUI) If Not @error Then GUICtrlSetData($sPathFileSave, $xPathFileSave) EndSwitch Sleep(1) WEnd Func NewClient($hSocket, $iError) GUICtrlSetData($listClient, $hSocket, $hSocket) _WriteLog("SERVER: New client connected/ Socket:" & $hSocket & " /Sending this: Welcome!") _TCP_Send($hSocket, "Welcome!") EndFunc ;==>NewClient Func Received($hSocket, $sReceived, $iError) _WriteLog("CLIENT: We received from Socket: " & $hSocket & " data: " & $sReceived) EndFunc ;==>Received Func Disconnect($hSocket, $iError) _WriteLog("SERVER: Client disconnected. Socket:" & $hSocket) EndFunc ;==>Disconnect Func _WriteLog($sLogMsg) Local $OldLog = GUICtrlRead($cDataReceived) GUICtrlSetData($cDataReceived, $OldLog & @CRLF & $sLogMsg) ;~ GUICtrlSetData($tStatus, $sLogMsg) ConsoleWrite("! " & $sLogMsg & @CRLF) $iEnd = StringLen(GUICtrlRead($tMessenger)) _GUICtrlEdit_SetSel($tMessenger, $iEnd, $iEnd) _GUICtrlEdit_Scroll($tMessenger, $SB_SCROLLCARET) $iEnd = StringLen(GUICtrlRead($cDataReceived)) _GUICtrlEdit_SetSel($cDataReceived, $iEnd, $iEnd) _GUICtrlEdit_Scroll($cDataReceived, $SB_SCROLLCARET) EndFunc ;==>_WriteLog Func GetIP($i = "ip") Local $return, $IP = StringSplit(BinaryToString(InetRead("http://api.wipmania.com/")), "<br>", 1) If $i = "from" Then If Not $IP[1] = "" Then $return = $IP[2] Else Return "Error: Api not responding." EndIf Else If Not $IP[1] = "" Then $return = $IP[1] Else Return "Error: Api not responding." EndIf EndIf Return $return EndFunc ;==>GetIP Client Script: #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <GUIConstantsEx.au3> #include <GuiEdit.au3> #include <GuiStatusBar.au3> #include <MsgBoxConstants.au3> #include <ScrollBarsConstants.au3> #include <WindowsConstants.au3> #include "TCP.au3" OnAutoItExitRegister("_OnExit") Func _OnExit() TCPShutdown() Exit EndFunc ;==>_OnExit #Region Global $hGUI = GUICreate("TCP AutoIT Client", 620, 400, -1, -1, -1, BitOR($WS_EX_ACCEPTFILES, $WS_EX_TOPMOST, $WS_EX_WINDOWEDGE)) Global $sMode = GUICtrlCreateRadio("Client Mode", 16, 8, 97, 17) GUICtrlSetState(-1, $GUI_CHECKED) Global $sConnectStatus = GUICtrlCreateLabel("", 408, 8, 89, 17) Global $sServerIP = GUICtrlCreateInput(@IPAddress1, 224, 8, 120, 21) Global $sServerPORT = GUICtrlCreateInput("8888", 345, 8, 39, 21) GUICtrlCreateLabel("IP Server:", 160, 10, 51, 17) Global $bStartConnect = GUICtrlCreateButton("Start Connect", 512, 6, 89, 33) Global $gMessenger = GUICtrlCreateGroup("Text to Send", 8, 64, 601, 129) Global $tMessenger = GUICtrlCreateEdit("", 15, 85, 489, 97, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "[START]kYtkjq1VuPTdNQtNlLuzUcEA56F4AaxlrhPZ3FSMd9Svss6Fflt0au6GMqMukNudNX02q7VqFVqJaaD0m5GG7hkGhg6TvblZDCZJ2YZNS1lj4t0hSmBly0nMBQYPDc3XTCUD3o4hZnROywXgaw713XHEeiuiXvu6UVXkVvlSdSlox8OkgEu0pk9zKYQJM0nfiiEaCbo4Rp6qKdDs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pnqTeRJxmrxvb4EuPGgd2jarO4aV05wKkjnmVSkpcurW7oZU6oEXRCqEzKXMGY4oBc8LbsZ4LMsVy2va1qpINqHQ3XBMO2FTDMUQIVL6ZKVCbiRHkSZbcb0YMjbneHvqjA8OxwhBIVJHR2u88hEeCPLnC6Aldtj8MStYd2MVX84JAbg2Ex9Z3xZ0e2XZQJLxKRIRq1AsZOe7s5HuIrbCNZIxzevnTPSMlhMilYrYbmQ3AmybdT20k0l99ELTVoU6tQeliov8LxEwpIgykKNSacSGBwayT0gH0EZpASsrs3rsv29NEOJzXtz94OgLiQU5BiZ5VyVl4MI4IPKyPvlog4LVgFV2qZSty9x9VXfeWTm8zxKOaBR1RV8Hi1sRw1peADLASmvCi9lQWWUw8fFFCAe5dUMhmrWGM8gGP919gKnqylw9GAl07pko9w1R6G3S1vKbvdjD9gSNXLQVf4M1G1CrfuHplDBZFGmfMrFA6uqZGptSZS2Kb4WZFCvkbcHgdDUlp2L05Oo7UhEJKhUs7hd[END]") Global $bSendMes = GUICtrlCreateButton("SEND", 511, 83, 89, 105) GUICtrlCreateGroup("", -99, -99, 1, 1) GUICtrlCreateLabel("File To Send:", 16, 200, 80, 17) Global $sPathFileSend = GUICtrlCreateInput(@TempDir & "\XXX.jpg", 104, 200, 361, 21) Global $bSelectFile = GUICtrlCreateButton(".!.", 472, 200, 35, 25) GUICtrlCreateLabel("Path To Save:", 16, 230, 80, 17) Global $sPathFileSave = GUICtrlCreateInput(@DesktopDir, 104, 230, 361, 21) Global $bSelectDir = GUICtrlCreateButton("...", 472, 230, 35, 25) Global $bSendFile = GUICtrlCreateButton("Send File", 512, 195, 89, 60) ;~ Global $tStatus = GUICtrlCreateLabel("", 16, 45, 580, 17) Global $gReceived = GUICtrlCreateGroup("Received", 8, 266, 601, 129) Global $cDataReceived = GUICtrlCreateEdit("", 16, 282, 585, 105, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL)) GUICtrlSetData(-1, "") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #EndRegion Global $hClient, $xSocket, $xServerIP, $xServerPORT, $xPathFileSend, $xPathFileSave While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $bStartConnect $xServerIP = GUICtrlRead($sServerIP) $xServerPORT = GUICtrlRead($sServerPORT) _WriteLog("Server Port: " & $xServerIP) _WriteLog("Server Port: " & $xServerPORT) $hClient = _TCP_Client_Create($xServerIP, $xServerPORT) ; Create the client. Which will connect to the local ip address on port xxxx _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. _WriteLog("CLIENT: Connecting...") Case $bSendFile ConsoleWrite("Send File Pressed!" & @CRLF) ;~ Exit Case $bSendMes $xMessenger = GUICtrlRead($tMessenger) _TCP_Send($xSocket, $xMessenger) ConsoleWrite("Send Messenger Pressed!" & @CRLF) Case $bSelectFile $xPathFileSend = FileOpenDialog("Select file to send:", @DesktopDir, "All (*.*)", 3, "", $hGUI) If Not @error Then GUICtrlSetData($sPathFileSend, $xPathFileSend) Case $bSelectDir $xPathFileSave = FileSelectFolder("Select local to save file received:", @DesktopDir, 0, @ScriptDir, $hGUI) If Not @error Then GUICtrlSetData($sPathFileSave, $xPathFileSave) EndSwitch Sleep(1) WEnd Func Connected($hSocket, $iError) If Not $iError Then _WriteLog("CLIENT: Connected!") GUICtrlSetData($bStartConnect, "Conneced") GUICtrlSetState($bStartConnect, $GUI_DISABLE) _WriteLog( "CLIENT: Conneced") ;~ _TCP_Send($hSocket, "Conneced :)") ;~ $xMessenger = GUICtrlRead($tMessenger) ;~ _TCP_Send($hSocket, $xMessenger) ;~ _WriteLog("CLIENT: Try reply socket: " & $hSocket & " data: " & $xMessenger) Else _WriteLog("CLIENT: Could not connect. Are you sure the server is running?") EndIf EndFunc ;==>Connected Func Received($hSocket, $sReceived, $iError) _WriteLog("CLIENT: We received from socket: " & $hSocket & " data: " & $sReceived) Sleep(1000) EndFunc ;==>Received Func Disconnect($hSocket, $iError) _WriteLog("SERVER: Client disconnected. Socket:" & $hSocket) EndFunc ;==>Disconnect Func _WriteLog($sLogMsg) Local $OldLog = GUICtrlRead($cDataReceived) GUICtrlSetData($cDataReceived, $OldLog & @CRLF & $sLogMsg) ;~ GUICtrlSetData($tStatus, $sLogMsg) ConsoleWrite("! " & $sLogMsg & @CRLF) $iEnd = StringLen(GUICtrlRead($tMessenger)) _GUICtrlEdit_SetSel($tMessenger, $iEnd, $iEnd) _GUICtrlEdit_Scroll($tMessenger, $SB_SCROLLCARET) $iEnd = StringLen(GUICtrlRead($cDataReceived)) _GUICtrlEdit_SetSel($cDataReceived, $iEnd, $iEnd) _GUICtrlEdit_Scroll($cDataReceived, $SB_SCROLLCARET) EndFunc ;==>_WriteLog Func GetIP($i = "ip") Local $return, $IP = StringSplit(BinaryToString(InetRead("http://api.wipmania.com/")), "<br>", 1) If $i = "from" Then If Not $IP[1] = "" Then $return = $IP[2] Else Return "Error: Api not responding." EndIf Else If Not $IP[1] = "" Then $return = $IP[1] Else Return "Error: Api not responding." EndIf EndIf Return $return EndFunc ;==>GetIP TCP.au3 #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.0.0 Author: Kip Script Function: TCP UDF v3 #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #cs Functions: _TCP_Server_Create($iPort, $sIP="0.0.0.0") _TCP_Server_Broadcast($sData) _TCP_Server_ClientList() _TCP_Server_ClientIP($hSocket) _TCP_Server_DisconnectClient($hSocket) _TCP_Server_Stop() _TCP_Client_Create($sIP , $iPort) _TCP_Client_Stop($hSocket) _TCP_Send($hSocket, $sText) _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) Register event values: $TCP_SEND ; Function ($hSocket, $iError) $TCP_RECEIVE ; Function ($hSocket, $sReceived, $iError) $TCP_CONNECT ; Function ($hSocket, $iError) => Client only $TCP_DISCONNECT ; Function ($hSocket, $iError) $TCP_NEWCLIENT ; Function ($hSocket, $iError) => Server only #ce Global Const $FD_READ = 1 Global Const $FD_WRITE = 2 Global Const $FD_OOB = 4 Global Const $FD_ACCEPT = 8 Global Const $FD_CONNECT = 16 Global Const $FD_CLOSE = 32 Global $hWs2_32 = -1 Global Const $TCP_SEND = 1 Global Const $TCP_RECEIVE = 2 Global Const $TCP_CONNECT = 4 Global Const $TCP_DISCONNECT = 8 Global Const $TCP_NEWCLIENT = 16 TCPStartup() Global Const $__TCP_WINDOW = GUICreate("Async Sockets UDF") Global $__TCP_SOCKETS[1][7] ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Create ; Description ...: Initializes the server. ; Syntax.........: _TCP_Server_Create($iPort, $sIP="0.0.0.0") ; Parameters ....: $iPort - The port number the server should listen to. ; $sIP - IP address. (Default = "0.0.0.0") ; Return values .: The socket handle. ; Author ........: Kip ; Modified.......: ; Remarks .......: Only 1 server can be created per script. ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Create($iPort, $sIP="0.0.0.0") Local $hListenSocket = ___ASocket() ___ASockSelect( $hListenSocket, $__TCP_WINDOW, 0x0400, $FD_ACCEPT) GUIRegisterMsg( 0x0400, "___TCP_OnAccept" ) ___ASockListen( $hListenSocket, $sIP, $iPort ) $__TCP_SOCKETS[0][0] = $hListenSocket $__TCP_SOCKETS[0][1] = 0x0400 Return $hListenSocket EndFunc Func ___TCP_OnAccept($hWnd, $iMsgID, $WParam, $LParam) Local $hSocket = $WParam Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $hClient, $uBound Abs($hWnd) ; Stupid AU3Check... If $iMsgID = $__TCP_SOCKETS[0][1] Then If $iEvent = $FD_ACCEPT Then If Not $iError Then ReDim $__TCP_SOCKETS[UBound($__TCP_SOCKETS)+1][7] $uBound = UBound($__TCP_SOCKETS) $hClient = TCPAccept($hSocket) ___ASockSelect($hClient, $__TCP_WINDOW, 0x0400 + $uBound - 1, BitOR($FD_READ, $FD_WRITE, $FD_CLOSE)) GUIRegisterMsg(0x0400 + $uBound - 1, "___TCP_Server_OnSocketEvent" ) $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][0] = $hClient $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][1] = 0x0400 + $uBound - 1 Call($__TCP_SOCKETS[0][6], $hClient, $iError) Else Call($__TCP_SOCKETS[0][6], 0, $iError) EndIf ElseIf $iEvent = $FD_CONNECT Then Call($__TCP_SOCKETS[0][4], $hSocket, $iError) EndIf EndIf EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Client_Stop ; Description ...: Stops the client. ; Syntax.........: _TCP_Client_Stop($hSocket) ; Parameters ....: $hSocket - Client socket. ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: The client socket is the return value of _TCP_Client_Create(). ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Client_Stop($hSocket) Local $iElement, $i $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iElement = $i ExitLoop EndIf Next If $iElement Then ___ASockShutdown($__TCP_SOCKETS[$iElement][0]) TCPCloseSocket($__TCP_SOCKETS[$iElement][0]) ___ArrayDelete($__TCP_SOCKETS, $iElement) Return True EndIf Return False EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Stop ; Description ...: Stops the server, and closes all client connections. ; Syntax.........: _TCP_Server_Stop() ; Parameters ....: ; Return values .: True ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Stop() Local $i ___ASockShutdown($__TCP_SOCKETS[0][0]) TCPCloseSocket($__TCP_SOCKETS[0][0]) $__TCP_SOCKETS[0][0] = "" $__TCP_SOCKETS[0][1] = "" $__TCP_SOCKETS[0][2] = "" $__TCP_SOCKETS[0][3] = "" $__TCP_SOCKETS[0][4] = "" $__TCP_SOCKETS[0][5] = "" $__TCP_SOCKETS[0][6] = "" For $i = UBound($__TCP_SOCKETS)-1 to 1 Step -1 ___ArrayDelete($__TCP_SOCKETS, $i) Next Return True EndFunc Func ___TCP_Server_OnSocketEvent( $hWnd, $iMsgID, $WParam, $LParam ) Local $hSocket = $WParam Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $sDataBuff, $iElement, $i Abs($hWnd) $hSocket = 0 $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][1] = $iMsgID Then $hSocket = $__TCP_SOCKETS[$i][0] $iElement = $i ExitLoop EndIf Next If $hSocket Then Switch $iEvent Case $FD_READ $sDataBuff = TCPRecv($hSocket, 1024) Call($__TCP_SOCKETS[0][2], $hSocket, $sDataBuff, $iError) Case $FD_WRITE Call($__TCP_SOCKETS[0][3], $hSocket, $iError) Case $FD_CLOSE ___ASockShutdown($hSocket) TCPCloseSocket($hSocket) Call($__TCP_SOCKETS[0][5], $hSocket, $iError) ___ArrayDelete($__TCP_SOCKETS, $iElement) EndSwitch EndIf EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_DisconnectClient ; Description ...: Disconnects a client of the server. ; Syntax.........: _TCP_Server_DisconnectClient($hSocket) ; Parameters ....: $hSocket - Client socket. ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: The client socket is the $hSocket parameter of a _TCP_RegisterEvent callback function. ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_DisconnectClient($hSocket) Local $iElement, $i $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iElement = $i ExitLoop EndIf Next If $iElement Then ___ASockShutdown($hSocket) TCPCloseSocket($hSocket) ___ArrayDelete($__TCP_SOCKETS, $iElement) Return True EndIf Return False EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_ClientList ; Description ...: Returns the sockets of all connected clients. ; Syntax.........: _TCP_Server_ClientList() ; Parameters ....: ; Return values .: An 1 dimensional array of all connected clients. ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_ClientList() Local $aReturn[1], $i For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] Then ReDim $aReturn[UBound($aReturn)+1] $aReturn[UBound($aReturn)-1] = $__TCP_SOCKETS[$i][0] EndIf Next $aReturn[0] = UBound($aReturn)-1 Return $aReturn EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_Broadcast ; Description ...: Sends data to all connected clients. ; Syntax.........: _TCP_Server_Broadcast($sData) ; Parameters ....: $sData - The data to send. ; Return values .: True ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_Broadcast($sData) Local $i For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] Then TCPSend($__TCP_SOCKETS[$i][0], $sData) Next Return True EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Client_Create ; Description ...: Creates a new client. ; Syntax.........: _TCP_Client_Create($sIP , $iPort) ; Parameters ....: $sIP - The IP address to connect to. ; $iPort - Port on which the created socket will be connected. ; Return values .: Client socket handle. ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Client_Create($sIP , $iPort) ReDim $__TCP_SOCKETS[UBound($__TCP_SOCKETS)+1][7] local $hSocket = ___ASocket() $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][0] = $hSocket $__TCP_SOCKETS[UBound($__TCP_SOCKETS)-1][1] = 0x0400 + (UBound($__TCP_SOCKETS)-1) ___ASockSelect( $hSocket, $__TCP_WINDOW, 0x0400 + (UBound($__TCP_SOCKETS)-1), BitOR( $FD_READ, $FD_WRITE, $FD_CONNECT, $FD_CLOSE ) ) GUIRegisterMsg( 0x0400 + (UBound($__TCP_SOCKETS)-1), "___TCP_Client_OnSocketEvent" ) ___ASockConnect( $hSocket, $sIP, $iPort ) Return $hSocket EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_RegisterEvent ; Description ...: Registers an event. ; Syntax.........: _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) ; Parameters ....: $hSocket - Socket of the server or a client. ; $iEvent - Event number. It can be any these values: ; * $TCP_SEND ; * $TCP_RECEIVE ; * $TCP_CONNECT => Client only ; * $TCP_DISCONNECT ; * $TCP_NEWCLIENT => Server only ; Return values .: Success - True ; Failure - False ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_RegisterEvent($hSocket, $iEvent, $sFunction) Local $iSelected = 0 Local $i If $__TCP_SOCKETS[0][0] Then $iSelected = 0 Else For $i = 0 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][0] = $hSocket Then $iSelected = $i ExitLoop EndIf Next If Not $iSelected Then Return 0 EndIf Switch $iEvent Case $TCP_SEND $__TCP_SOCKETS[$iSelected][3] = $sFunction Case $TCP_RECEIVE $__TCP_SOCKETS[$iSelected][2] = $sFunction Case $TCP_CONNECT $__TCP_SOCKETS[$iSelected][4] = $sFunction Case $TCP_DISCONNECT $__TCP_SOCKETS[$iSelected][5] = $sFunction Case $TCP_NEWCLIENT $__TCP_SOCKETS[$iSelected][6] = $sFunction Case Else Return False EndSwitch Return True EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Server_ClientIP ; Description ...: Converts a client socket handle to IP address. ; Syntax.........: _TCP_Server_ClientIP($hSocket) ; Parameters ....: $hSocket - Client socket handle. ; Return values .: A string with the IP address. ; Author ........: Unknown ; Modified.......: Kip ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Server_ClientIP($hSocket) Local $pSocketAddress, $aReturn $pSocketAddress = DllStructCreate("short;ushort;uint;char[8]") $aReturn = DllCall("Ws2_32.dll", "int", "getpeername", "int", $hSocket, "ptr", DllStructGetPtr($pSocketAddress), "int*", DllStructGetSize($pSocketAddress)) If @error Or $aReturn[0] <> 0 Then Return 0 $aReturn = DllCall("Ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($pSocketAddress, 3)) If @error Then Return 0 $pSocketAddress = 0 Return $aReturn[0] EndFunc ; #FUNCTION# ;=============================================================================== ; ; Name...........: _TCP_Send ; Description ...: Sends data to a server or client. ; Syntax.........: _TCP_Send($hSocket, $sText) ; Parameters ....: $hSocket - Client or server socket handle. ; $sText - Data to send. ; Return values .: ; Author ........: Kip ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; ; ; ;========================================================================================== Func _TCP_Send($hSocket, $sText) Return TCPSend($hSocket, $sText) EndFunc Func ___TCP_Client_OnSocketEvent( $hWnd, $iMsgID, $WParam, $LParam ) Local $iError = ___HiWord( $LParam ) Local $iEvent = ___LoWord( $LParam ) Local $hSocket, $iElement, $i, $sDataBuff Abs($hWnd) Abs($WParam) $hSocket = 0 $iElement = 0 For $i = 1 to UBound($__TCP_SOCKETS)-1 If $__TCP_SOCKETS[$i][1] = $iMsgID Then $hSocket = $__TCP_SOCKETS[$i][0] $iElement = $i ExitLoop EndIf Next If $hSocket Then Switch $iEvent Case $FD_READ; Data has arrived! $sDataBuff = TCPRecv( $hSocket, 1024) Call($__TCP_SOCKETS[$i][2], $hSocket, $sDataBuff, $iError) $sDataBuff = "" Case $FD_WRITE Call($__TCP_SOCKETS[$i][3], $hSocket, $iError) Case $FD_CONNECT Call($__TCP_SOCKETS[$i][4], $hSocket, $iError) Case $FD_CLOSE ___ASockShutdown( $hSocket ) TCPCloseSocket( $hSocket ) Call($__TCP_SOCKETS[$i][5], $hSocket, $iError) ___ArrayDelete($__TCP_SOCKETS, $iElement) EndSwitch EndIf EndFunc ;================================================================================================================== ; ; Zatorg's Asynchronous Sockets UDF Starts from here. ; ;================================================================================================================== Func ___ASocket($iAddressFamily = 2, $iType = 1, $iProtocol = 6) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $hSocket = DllCall($hWs2_32, "uint", "socket", "int", $iAddressFamily, "int", $iType, "int", $iProtocol) If @error Then SetError(1, @error) Return -1 EndIf If $hSocket[ 0 ] = -1 Then SetError(2, ___WSAGetLastError()) Return -1 EndIf Return $hSocket[ 0 ] EndFunc ;==>_ASocket Func ___ASockShutdown($hSocket) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "shutdown", "uint", $hSocket, "int", 2) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockShutdown Func ___ASockClose($hSocket) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "closesocket", "uint", $hSocket) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockClose Func ___ASockSelect($hSocket, $hWnd, $uiMsg, $iEvent) If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall( _ $hWs2_32, _ "int", "WSAAsyncSelect", _ "uint", $hSocket, _ "hwnd", $hWnd, _ "uint", $uiMsg, _ "int", $iEvent _ ) If @error Then SetError(1, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then SetError(2, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockSelect ; Note: you can see that $iMaxPending is set to 5 by default. ; IT DOES NOT MEAN THAT DEFAULT = 5 PENDING CONNECTIONS ; 5 == SOMAXCONN, so don't worry be happy Func ___ASockListen($hSocket, $sIP, $uiPort, $iMaxPending = 5); 5 == SOMAXCONN => No need to change it. Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = ___SockAddr($sIP, $uiPort) If @error Then SetError(@error, @extended) Return False EndIf $iRet = DllCall($hWs2_32, "int", "bind", "uint", $hSocket, "ptr", DllStructGetPtr($stAddress), "int", DllStructGetSize($stAddress)) If @error Then SetError(3, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then $stAddress = 0; Deallocate SetError(4, ___WSAGetLastError()) Return False EndIf $iRet = DllCall($hWs2_32, "int", "listen", "uint", $hSocket, "int", $iMaxPending) If @error Then SetError(5, @error) Return False EndIf If $iRet[ 0 ] <> 0 Then $stAddress = 0; Deallocate SetError(6, ___WSAGetLastError()) Return False EndIf Return True EndFunc ;==>_ASockListen Func ___ASockConnect($hSocket, $sIP, $uiPort) Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = ___SockAddr($sIP, $uiPort) If @error Then SetError(@error, @extended) Return False EndIf $iRet = DllCall($hWs2_32, "int", "connect", "uint", $hSocket, "ptr", DllStructGetPtr($stAddress), "int", DllStructGetSize($stAddress)) If @error Then SetError(3, @error) Return False EndIf $iRet = ___WSAGetLastError() If $iRet = 10035 Then; WSAEWOULDBLOCK Return True; Asynchronous connect attempt has been started. EndIf SetExtended(1); Connected immediately Return True EndFunc ;==>_ASockConnect ; A wrapper function to ease all the pain in creating and filling the sockaddr struct Func ___SockAddr($sIP, $iPort, $iAddressFamily = 2) Local $iRet Local $stAddress If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) $stAddress = DllStructCreate("short; ushort; uint; char[8]") If @error Then SetError(1, @error) Return False EndIf DllStructSetData($stAddress, 1, $iAddressFamily) $iRet = DllCall($hWs2_32, "ushort", "htons", "ushort", $iPort) DllStructSetData($stAddress, 2, $iRet[ 0 ]) $iRet = DllCall($hWs2_32, "uint", "inet_addr", "str", $sIP) If $iRet[ 0 ] = 0xffffffff Then; INADDR_NONE $stAddress = 0; Deallocate SetError(2, ___WSAGetLastError()) Return False EndIf DllStructSetData($stAddress, 3, $iRet[ 0 ]) Return $stAddress EndFunc ;==>__SockAddr Func ___WSAGetLastError() If $hWs2_32 = -1 Then $hWs2_32 = DllOpen( "Ws2_32.dll" ) Local $iRet = DllCall($hWs2_32, "int", "WSAGetLastError") If @error Then ;ConsoleWrite("+> _WSAGetLastError(): WSAGetLastError() failed. Script line number: " & @ScriptLineNumber & @CRLF) SetExtended(1) Return 0 EndIf Return $iRet[ 0 ] EndFunc ;==>_WSAGetLastError ; Got these here: ; http://www.autoitscript.com/forum/index.php?showtopic=5620&hl=MAKELONG Func ___MakeLong($LoWord, $HiWord) Return BitOR($HiWord * 0x10000, BitAND($LoWord, 0xFFFF)); Thanks Larry EndFunc ;==>_MakeLong Func ___HiWord($Long) Return BitShift($Long, 16); Thanks Valik EndFunc ;==>_HiWord Func ___LoWord($Long) Return BitAND($Long, 0xFFFF); Thanks Valik EndFunc ;==>_LoWord ; ========================================= Array functions ; #FUNCTION# ==================================================================================================================== ; Name...........: _ArrayDelete ; Description ...: Deletes the specified element from the given array. ; Syntax.........: _ArrayDelete(ByRef $avArray, $iElement) ; Parameters ....: $avArray - Array to modify ; $iElement - Element to delete ; Return values .: Success - New size of the array ; Failure - 0, sets @error to: ; |1 - $avArray is not an array ; |3 - $avArray has too many dimensions (only up to 2D supported) ; |(2 - Deprecated error code) ; Author ........: Cephas <cephas at clergy dot net> ; Modified.......: Jos van der Zande <jdeb at autoitscript dot com> - array passed ByRef, Ultima - 2D arrays supported, reworked function (no longer needs temporary array; faster when deleting from end) ; Remarks .......: If the array has one element left (or one row for 2D arrays), it will be set to "" after _ArrayDelete() is used on it. ; Related .......: _ArrayAdd, _ArrayInsert, _ArrayPop, _ArrayPush ; Link ..........; ; Example .......; Yes ; =============================================================================================================================== Func ___ArrayDelete(ByRef $avArray, $iElement) If Not IsArray($avArray) Then Return SetError(1, 0, 0) Local $iUBound = UBound($avArray, 1) - 1 If Not $iUBound Then $avArray = "" Return 0 EndIf ; Bounds checking If $iElement < 0 Then $iElement = 0 If $iElement > $iUBound Then $iElement = $iUBound ; Move items after $iElement up by 1 Switch UBound($avArray, 0) Case 1 For $i = $iElement To $iUBound - 1 $avArray[$i] = $avArray[$i + 1] Next ReDim $avArray[$iUBound] Case 2 Local $iSubMax = UBound($avArray, 2) - 1 For $i = $iElement To $iUBound - 1 For $j = 0 To $iSubMax $avArray[$i][$j] = $avArray[$i + 1][$j] Next Next ReDim $avArray[$iUBound][$iSubMax + 1] Case Else Return SetError(3, 0, 0) EndSwitch Return $iUBound EndFunc ;==>_ArrayDelete Problem: - Can not send and receive between Client and Server! - Data loss, data reception is not complete.
  4. Reproducer... TCPStartup() ; TCPConnect('212.227.91.231', '80') Local $error = @error MsgBox(0, 'AutoIt Version: ' & @AutoItVersion, 'AutoIt Error: ' & $error & @CRLF & 'WSAError: ' & _WSAGetLastErrorEx() & @TAB) TCPShutDown() ; Func _WSAGetLastErrorEx() Local $a = DllCall('ws2_32.dll', 'int', 'WSAGetLastError') If @error Or Not IsArray($a) Then Return SetError(1, 0, 'FuncError -1') $a = DllCall('kernel32.dll', 'int', 'FormatMessage', 'int', 0x00001000, 'ptr', 0, 'int', $a[0], 'int', 0, 'str', 0, 'int', 2048, 'ptr', 0) If @error Or Not IsArray($a) Then Return SetError(1, 0, 'FuncError -2') Return $a[3] & ' - ' & StringStripWS($a[5], 7) EndFunc Tested: autoit-v3.3.12.0, autoit-v3.3.14.0 and autoit-v3.3.15.0 beta on Win7. Seems to have started with autoit-v3.3.14.0.
  5. This script is based on algorithm code from EnrMa. Updated: January 07, 2017 Changes are in the script header. LocalProxyServer_v0.15b.au3 Known Issues: POST is not working consistently in uploading files. AutoIt x64 does not work properly with this script.
  6. Hello Everyone this is the first time to post a problem with autoit, I have been using it for more than 3 years but im still feel new I have a VPS running online game , -snip-
  7. Hello everybody, I'm making an program witch reads packets from server/client, first of all it reads size of the packet(it may be 1-5 bytes in size), and then reads what's left. Problem: TCPRecv($socket,1,1) tooks really long to receive 1 byte, most of the time 100ms! You can see packets here and how much time it took to read size of them(1-5 bytes, all of them are 1 byte in size): 0xAA63 (99.8802703210873ms) 0x53 (99.8829718030123ms) 0x2B (99.7435753356861ms) 0x4E (100.176352740059ms) I want to interrupt sometimes server or client, send packets, but I cannot send packets if server/client didn't get last packet. Sometimes packets are huge(16MB or even more), sometimes they are 2-6 bytes in size. I just don't want to receive everything and just send it. I want to see every packet, and collect data from these packets. EDIT: I receive couple packets at the same time with TCPRecv to make it faster. I use TCPRecv($socket,10000,1). It made program a bit faster... But still, when receiving again these packets, it still tooks 100ms. It's still slow. How to make TCPRecv($socket,1,1) faster? I don't need any error checking or etc., just to make it as fast as possible. (I only receive everything in hexadecimal) I really need help with this... It's so slow and annoying!
  8. If you are talking using text based protocols, Kip's TCP.au3 event driven UDF is great. But what happens if you want to talk to a 3rd party providers device/software that talks using binary format data in packet form? What if the packet size is variable? PTCP is a wrapper around Kip's TCP.au3 that lets you focus on dealing with the packets, rather than figuring out how to determine if there is a complete packet available etc. For sending, you just send a binary string (the actual packet data) For receiving, you just get a complete packet - even if the packet size is variable! How? When you connect, you pass an AutoIt expression that tells PTCP how to tell if a packet is complete. For fixed sized packets, that's easy - just pass the number of bytes. For variable length packets, the expression can contain references to the packet data itself, as well as the number of bytes currently in the Rx buffer. This means you can specify the packet size as some combination of bytes in the packet. An example might be: "($iAvail>7)?((BitAND(BinaryMid($aPacket,7,1), '0xff'))+(BitShift(BitAND(BinaryMid($aPacket,8,1),'0xff'),-8))+8):(0)" This says: we need at least 8 bytes of the packet to know the packet size; once we have these 8 bytes, the packet size is stored in bytes 7 & 8 as little-endian (LSB first) Other than the packetizing details, it's pretty much just Kip's event driven TCP code. Hope you find it useful. PTCP.au3
  9. I've a problem with receiving data on my PC by TCP and UDP. I can send data to another computer, but can't receive it. I'm not shure where is the problem (on PC or on "another comupers") This is client code: ;TCP client TCPStartup() $socket = TCPConnect("192.168.0.18", 7777) ;try to connect to server and save number of socket If $socket = -1 Then ;if $socket = -1 then error MsgBox(16, "Error:", "Can't connect to server") EndIf $sendedBytes = TCPSend($socket, "nothing here :)") ;send message to connected socket If $sendedBytes = 0 Then ;if receiving data TCPSend(...) = 0 then error MsgBox(16, "Error", "Can't send message") EndIf TCPCloseSocket($socket) TCPShutdown() and server code: ;TCP server TCPStartup() $mainsocket = TCPListen("192.168.0.18", 7777) ;making main receiving socket While 1 ;receiving loop $acceptedSocket = TCPAccept($mainsocket) ;possible connection to accept If $acceptedSocket <> -1 Then $receivedData = TCPRecv($acceptedSocket, 1024) ;if main socket is connected then receive message MsgBox(64, "Received message!", "Message: " & $receivedData) TCPCloseSocket($acceptedSocket) ;close open connecion EndIf WEnd TCPShutdown() When server is on PC I can't receive any messages from any other computers. When client is on PC I can receive messages on any another computer. I tried to turn off antiviruses and windows firewall but it did't change anything EDIT: Error code from client from TCPConnect is 10060 (connection time out) and from TCPSend: 10038 I've found something about 10060 error code, Microsoft says "Connection timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond." So it means that the problem is with time of response but it makes no sense couse "another computer" is Virtual Machine with bridge internet connection from PC (pings beetwen PC and VM are lower than 1ms. About 10038 error code microsoft says that this is problem with socket and it actually makes sense.
  10. Hi, when a client sends /logout to the server i want that the server find the id of the client and set his online status to 0 Using 'default' I have no problems, but when I do this with 'blank517' gives me id 10 and then for the database remains online Database while Blank517 logout: id | username | password | permissions | online | 0 | default | pass1 | 0 | 0 | 1 | Blank517 | pass | 0 | 1 | Server recv: Func _Recv_From_Sockets_() For $0 = 1 To $max_connections $Recv = TCPRecv ($Socket_Data[$0][0],1024) If StringLeft($Recv, 1) = "/" Then If StringInStr($Recv, "logout") Then _SQLite_Query(-1, "SELECT id FROM Users WHERE username = '" & $Socket_Data[$0][1] & "' AND online = '1';", $hQuery) While _SQLite_FetchData($hQuery, $aRow) = $SQLITE_OK $sMsg &= $aRow[0]; <-- $sMsg = 10 after FetchData WEnd _SQLite_Exec(-1, "UPDATE Users SET online = '0' WHERE id = '" & $sMsg & "';") For $000 = 1 To $max_connections TCPSend($Socket_Data[$000][0], $Socket_Data[$0][1] & " ha effettuato il logout") Next TCPCloseSocket($Socket_Data[$0][0]) $sMsg = Null EndIf Else _Broadcast_To_Sockets_ ($Recv) EndIf Next EndFunc *excuse me for my bad english *
  11. Hello every body! I am trying to dev an simple chat using TCP. but it don't work for me. Please help me. I want to in 1 second, Client will send to server a message. And then, Server recv this message and write to Console. But when i run server and client. In server, i was recv only one message. Please tell me why? In server, i code: #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> Global $r = @CRLF; Global $ip = "127.0.0.1" Global $port = 1337 Global $client, $iSocket TCPStartup() $iSocket = TCPListen($ip, $port) While 1 $client = TCPAccept($iSocket) If $client <> -1 Then TCPSend($client, "Client is Connected"); EndIf $msg = TCPRecv($client, 1024) if StringLen($msg) <>0 Then ConsoleWrite("Server recv: " &$msg) EndIf TCPSend($client, "Send this msg to client"); Sleep(1000) WEnd In client, i code: #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> Global $ip = "127.0.0.1" Global $port = 1337 Global $r = @CRLF; TCPStartup() $server = TCPConnect($ip, $port) While 1 TCPSend($server, "Send msg to server") Sleep(1000) WEnd
  12. This topic will contain simple and working client server communication example along with some basic info for understanding. Examples are based on multi client communication that is happening on one computer (localhost). Changing (if it's not already set correctly) the IP address parameter on server script to reflect your network device IP address will allow you to communicate with other clients on network or even to communicate on internet if your network settings (forwarded router port, ip address on that port is seen from others on internet, you're not trying to do client server from identical computer on identical internet connection) are configured correctly. Every client connecting will need to have server IP address for network (or server public IP address for internet) connection in his client script. So edit client script to correspond to server address TCPConnect('type server ip address in client', 1018). Sometimes firewall can be your problem, if something isn't working turn off firewall and see if it helps. Server will always listen on his Network Adapter IP Address and not on his public address. In some rare occasions server can be set to listen on 0.0.0.0, with that he will listen from any device that he have physically connected on his MB USB or something third (with localhost included for listening). But i would not know the end result of what will happen if some other program that you have installed need that port (or you started 2 servers that interpret one with another). First part will hold just plain code.Second part will hold identical code with comments below commands for more info and understanding hopefully to help new autoit users to understand what and why that something is there.Other parts will hold additional info.First part: Working Code (working in two way communication, with multiple and-or identical client)Server #include <Array.au3> TCPStartup() Dim $Socket_Data[1] $Socket_Data[0] = 0 $Listen = TCPListen(@IPAddress1, 1018, 500) If @error Then ConsoleWrite('!--> TCPListen error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPListen to get more info about this error.' & @CRLF) Exit EndIf While 1 For $x = $Socket_Data[0] To 1 Step -1 $Recv = TCPRecv($Socket_Data[$x], 1000000) If $Recv Then MsgBox(0, 'Client Number ' & $x & ' with connected socket identifier ' & $Socket_Data[$x], 'Recived msg from Client: ' & @CRLF & $Recv, 5) TCPSend($Socket_Data[$x], 'bye') TCPCloseSocket($Socket_Data[$x]) _ArrayDelete($Socket_Data, $x) $Socket_Data[0] -= 1 EndIf Next _Accept() WEnd Func _Accept() Local $Accept = TCPAccept($Listen) If $Accept <> -1 Then _ArrayAdd($Socket_Data, $Accept) $Socket_Data[0] += 1 EndIf EndFunc ;==>_AcceptClient TCPStartup() $Socket = TCPConnect(@IPAddress1, 1018) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPConnect to get more info about this error.' & @CRLF) Exit EndIf TCPSend($Socket, 'Hi there. My computer name is' & ", " & @ComputerName & ", and its drive serial is " & DriveGetSerial(@HomeDrive)) Do $Recv = TCPRecv($Socket, 1000000) Until $Recv MsgBox(0, 'Recived from server:', $Recv)Second part: Explained Working Code (for upper communication) Third Part: Understanding for how is msg received with TCPRecv on server (or on client) Forth Part: Packets Fifth Part: How to get or check IP address of your device? Sixth Part: How to forward ports? (2 nice youtube tutorials) Seventh Part: Internet communication? If i wrote something incorrectly or wrong please tell me so that i can correct it. Edited: Local and Global, added aditional info about reciving msgs for maxlen buffer.
  13. I was just working on a project that involved decoding a stream of binary data from a serial port in AutoIt. It took me a few hours to figure out how to process the data efficiently in AutoIt and I did not find any helpful examples on how to do so, so I thought I would share my core example and maybe save someone else some time. There may be a more efficient way to do this, but this works well for me. #cs Author: ToasterKing This is an example of a way to parse streaming binary data that follows a strict format with a header and footer. In this example, each frame is 5 bytes with a 2-byte header of 0xD5AA and a 1-byte footer of 0xAD. The _BinaryParse() function accumulates incoming data in a buffer. Once a footer is found, it searches backward for the header, and if it is in the right position, it extracts the remaining 2 bytes in the middle, then moves on to looking for the next frame. #ce ; The data source might be something asynchronous like serial or TCP, but since this is just an example, I'm just putting the data in a variable. Local $fSomeData $fSomeData = Binary("0xD5AA24B1") ; Binary data constituting almost a complete frame. _BinaryParse($fSomeData) ; Call the function with the received data. It isn't a complete frame, so it is just stored in the buffer until more data is received. $fSomeData = Binary("0xAD62D5AA92E7AD") ; Remainder of the previous frame, one garbage byte (0x62) which should be skipped, and a complete additional frame. _BinaryParse($fSomeData) ; The function should be able to parse both frames now. Func _BinaryParse($fNewData) Local Static $fBinaryReceived = Binary("") ; Buffer for received data ConsoleWrite("Hey, the function is called!" & @CRLF) ; Add new data to the buffer. ; This ridiculous monstrosity is the only way I could find to append binary data to binary data in AutoIt. It must be converted to strings first. ; Both, one, or no substrings will begin with "0x" depending on whether they contained binary data. To be converted back to binary properly, only one instance ; of "0x" must exist at the beginning of the string. $fBinaryReceived = Binary("0x" & StringReplace(String($fBinaryReceived) & String($fNewData),"0x","")) ConsoleWrite("Data in the buffer: " & String($fBinaryReceived) & @CRLF) Local $iLength = BinaryLen($fBinaryReceived) ; Count the bytes in the data If $iLength > 0 Then Local $fBinaryReceivedTemp = $fBinaryReceived ; Create temporary copy to work on Local $fByte1,$fByte2 For $i = 1 To $iLength If BinaryMid($fBinaryReceivedTemp,$i,1) = 0xAD Then ; If the 1-byte footer found ConsoleWrite("Footer found at end of " & $i & " of " & $iLength & " bytes!" & @CRLF) If BinaryMid($fBinaryReceivedTemp,$i - 4,1) = 0xD5 And BinaryMid($fBinaryReceivedTemp,$i - 3,1) = 0xAA Then ; and the 2-byte header is found 4 bytes before that ConsoleWrite("Header found before the footer!" & @CRLF) $fByte1 = BinaryMid($fBinaryReceivedTemp,$i - 2,1) ; Get 1st byte in the body (between header and footer) $fByte2 = BinaryMid($fBinaryReceivedTemp,$i - 1,1) ; Get 2nd byte in the body (between header and footer) ConsoleWrite("Here is the critical data: " & String($fByte1) & " " & String($fByte2) & @CRLF) ; Just display the 2 bytes for demonstration purposes. Normally, you'd do something more useful with it here. EndIf $fBinaryReceived = BinaryMid($fBinaryReceivedTemp,$i + 1) ; Truncate the original data to remove all of the bytes just processed, then continue processing $fBinaryReceivedTemp EndIf Next EndIf EndFunc
  14. Network Interface Info, Statistics, and Traffic (incl. IP, TCP, UDP and ICMP) This is an example of getting and displaying Network Interface Information, Statistics and Traffic. Previously this was just a means to getting Network statistics (specifically IP, TCP, UDP, and ICMP), but now it includes Internet Interface information, as well as Interface-specific statistics. Since this UDF can be used in different ways, let me cover Statistics first: Network Statistics Information Stats example output To retrieve Statistics information, you can call one of the four _Network_xxxxStatistics() functions for IP, TCP, UDP, or ICMP Statistics. These functions accept 1 argument which specifies which protocol to use. Basically, zero is IPv4 and non-zero is IPv6. It defaults to IPv4 if no arguments. Here's the functions: Protocol Statistics Functions: _Network_IPStatistics() -> receives IP statistics _Network_TCPStatistics() -> TCP statistics _Network_UDPStatistics() -> UDP statistics _Network_ICMPStatistics() -> ICMP statistics - To get per-interface statistics requires 2 calls. One call is required to collect information on adapters into an array. Once this information is retrieved, multiple calls to _Network_InterfaceEntryInfo() can be made for each indexed network interface. Note that _Network_IPv4AdaptersInfo() is the only adapter/interface information function which doesn't get index information - so don't use it unless you want further interface information. The main UDF functions to use are: Network Adapter & Interface Functions: _Network_IPv4AdaptersInfo() -> Retrieves information on Physical IPv4 adapters _Network_IPv4AdaptersInfoEx() -> Retrieves much more info on Physical IPv4 adapters _Network_IPv4AddressTable() -> Retrieves information on IPv4 Interfaces _Network_IPAllAddressTable() -> Retrieves information on both IPv4 and IPv6 interfaces Network Statistics for a Given Interface: _Network_InterfaceEntryInfo() -> For a given interface index, retrieves statistics - The simplest way to get overall traffic is to use _Network_IPAllAddressTable() (or _Network_IPv4AddressTable() for IPv4 only) to collect an array of info about interfaces. This needs to be done only once. Then, to collect statistics, for each row in the interface array, call _Network_InterfaceEntryInfo() with $aIPAddressTable[$i][0] to get the statistics for that network interface. IMPORTANT: Note that for all statistics, the data received/sent are represented as 32-bit numbers, and subject to wraparound after 4GBs of data has been transferred. Network Interface Information Regarding Network Interface Information, nearly every function except those ending in xxStatistics(), will return various info regarding the network adapters or interfaces. Currently, IPv4 and IPv6 addresses are retrieved for the interface, as well as for Gateway, DHCP, DNS and WINS servers (there's some XP issues here as to which functions to use - see UDFs). The number of IP addresses (since there can be more than one assigned to each interface) is controlled via a parameter $bGetAllIPs. If this value is non-zero, multiple IP addresses are returned in a string separated by "|" (pipe symbol). Also note that the MAC/Physical Address is returned by most functions as well. These are properly formatted into a hex string in the form "01-23-45-67-89-ab". There is one issue with converting IPv6 addresses - on pre-Vista O/S's (Win XP I'm looking at you) WSAStartup must be called by the code. This is all handled internally, but if you have code that relies on WSAStartup/Cleanup, keep it in mind and let me know if I can better accommodate any potential conflicts. Further notes: - The TCP Statistics gives information about the number of segments sent/received, rather than the # of packets. I'm not totally clear on the association, however here's some links: What's the difference between a TCP segment and a TCP packet? Whats the difference between a Packet, Segment and Frame? - I'm not sure how segments, packets, or datagrams map to # of bytes, or what API functions I might use to figure this out. Any help there would be appreciated. Alternatives: While I have opened access to a lot of detailed network and performance information, there are alternatives - check out Netstat (-e for performance stats) or my >Performance Counters UDF's, which has a lot of varied stats (one example of these: >Network Usage). Following is the example, included in the ZIP file. Note there's a cr@pload of info dumped to the console, so you'll probably want to redirect output or copy-and-paste from the output console: ; ======================================================================================================== ; <NetworkStatsExample.au3> ; ; Example of reading and displaying Network Interface Information and Statistics ; (using <NetworkStatistics.au3> UDF) ; Statistics information, including IP, TCP*, UDP, and ICMP and internet interface traffic, ; are displayed in a 'Splash' window - with both IPv4 and IPv6 data separated ; ; Author: Ascend4nt ; ======================================================================================================== #include "_NetworkStatistics.au3" ; -------------------- HOTKEY FUNCTION & VARIABLE -------------------- Global $bHotKeyPressed = False Func _EscPressed() $bHotKeyPressed=True EndFunc ; -------------------- MAIN PROGRAM CODE -------------------- HotKeySet("{Esc}", "_EscPressed") Local $hSplash, $sSplashText ; Network Stats Local $aUDPStats, $aTCPStats, $aIPStats, $aICMPStats Local $aUDPv6Stats, $aTCPv6Stats, $aIPv6Stats, $aICMPv6Stats Local $aIPv4Adapters, $nAdapters Local $aIPv4AddrTable, $aIPAllAddrTable, $nInterfaces, $aNIEntryInfo Local $sSeparator = "-----------------------------------------" ; IP Stats: IPv4 and IPv6 For $i = 0 To 1 $aIPStats = _Network_IPStatistics($i) If @error Then ConsoleWrite("_Network_IPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("IP [IPv6] Stats:") Else ConsoleWrite("IP [IPv4] Stats:") EndIf ConsoleWrite( _ " [0] = IP Forwarding Status: [1 = Enabled, 2 = Disabled] : " & $aIPStats[0] & _ ", [1] = Default initial time-to-live (TTL) for datagrams : " & $aIPStats[1] & @CRLF & _ ", [2] = # Received Datagrams : " & $aIPStats[2] & _ ", [3] = # Received Datagrams w/Header errors : " & $aIPStats[3] & _ ", [4] = # Received Datagrams w/Address errors : " & $aIPStats[4] & @CRLF & _ ", [5] = # Forwarded Datagrams : " & $aIPStats[5] & _ ", [6] = # Received Datagrams w/Unknown Protocol : " & $aIPStats[6] & _ ", [7] = # Received Datagrams Discarded : " & $aIPStats[7] & @CRLF & _ ", [8] = # Received Datagrams Delivered : " & $aIPStats[8] & _ ", [9] = # Requested Outgoing Datagrams : " & $aIPStats[9] & _ ", [10] = # Outgoing Datagrams Discarded : " & $aIPStats[10] & @CRLF & _ ", [11] = # Transmitted Datagrams Discarded : " & $aIPStats[11] & _ ", [12] = # Datagrams w/o Routes that were Discarded : " & $aIPStats[12] & _ ", [13] = TimeOut for Reassembling Incoming Fragmented Datagrams : " & $aIPStats[13] & @CRLF & _ ", [14] = # Datagrams Requiring Reassembly : " & $aIPStats[14] & _ ", [15] = # Datagrams Successfully Reassembled : " & $aIPStats[15] & _ ", [16] = # Datagrams that Failed to be Reassembled : " & $aIPStats[16] & @CRLF & _ ", [17] = # Datagrams that were Fragmented Successfully : " & $aIPStats[17] & _ ", [18] = # Datagrams not Fragmented, and Discarded : " & $aIPStats[18] & _ ", [19] = # Fragments created (for Datagrams) : " & $aIPStats[19] & @CRLF & _ ", [20] = # of Interfaces : " & $aIPStats[20] & _ ", [21] = # of IP addresses associated with PC : " & $aIPStats[21] & _ ", [22] = # of Routes in the Routing table : " & $aIPStats[22] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; TCP Stats: IPv4 and IPv6 For $i = 0 To 1 $aTCPStats = _Network_TCPStatistics($i) If @error Then ConsoleWrite("_Network_TCPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("TCP [IPv6] Stats:") Else ConsoleWrite("TCP [IPv4] Stats:") EndIf ConsoleWrite( _ "[0] Rto Algorithm = " & $aTCPStats[0] & _ ",[1] Rto Min = " & $aTCPStats[1] & _ ",[2] Rto Max = " & $aTCPStats[2] & _ ",[3] #Max Connections = " & $aTCPStats[3] & _ ",[4] #Active Opens = " & $aTCPStats[4] & _ ",[5] #Passive Opens = " & $aTCPStats[5] & @CRLF & _ " [6] #Failed Connection Attempts = " & $aTCPStats[6] & _ ",[7] #Established Connections that were Reset = " & $aTCPStats[7] & _ ",[8] #Established Connections [current] = " & $aTCPStats[8] & @CRLF & _ " [9] #Recvd Segments = " & $aTCPStats[9] & _ ",[10] #Sent Segments = " & $aTCPStats[10] & _ ",[11] #Retransmitted Segments = " & $aTCPStats[11] & @CRLF & _ " [12] #Receive Errors = " & $aTCPStats[12] & _ ",[13] #Sent Segments with Reset Flag = " & $aTCPStats[13] & _ ",[14] #Connections = " & $aTCPStats[14] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; UDP Stats: IPv4 and IPv6 For $i = 0 To 1 $aUDPStats = _Network_UDPStatistics($i) If @error Then ConsoleWrite("_Network_UDPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf If $i Then ConsoleWrite("UDP [IPv6] Stats:") Else ConsoleWrite("UDP [IPv4] Stats:") EndIf ConsoleWrite( _ " [0] #Recvd Datagrams = " & $aUDPStats[0] & _ ",[1] #Discarded Datagrams [invalid port] = " & $aUDPStats[1] & _ ",[2] #Erroneous Datagrams = " & $aUDPStats[2] & @CRLF & _ " [3] #Sent Datagrams = " & $aUDPStats[3] & _ ",[4] #UDP Listener Entries = " & $aUDPStats[4] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; ICMP Stats: IPv4 and IPv6 For $i = 0 To 1 $aICMPStats = _Network_ICMPStatistics($i) If @error Then ConsoleWrite("_Network_ICMPStatistics("&$i&") error: "&@error&", @extended="&@extended&@CRLF) ContinueLoop EndIf ConsoleWrite("ICMP [IPv"&4+($i*2)&"] Stats:" & _ " [0] = # Incoming ICMP Messages : " & $aICMPStats[0] & _ ", [1] = # Incoming ICMP Errors : " & $aICMPStats[1] & _ ", [2] = # Outgoing ICMP Messages : " & $aICMPStats[2] & _ ", [3] = # Outgoing ICMP Errors : " & $aICMPStats[3] & _ @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; IPv4 Adapters Info (very basic info) _Network_IPv4AdaptersInfo() ConsoleWrite($sSeparator & @CRLF) ; IPv4 Adapters Info (comprehensive info) $aIPv4Adapters = _Network_IPv4AdaptersInfoEx() $nAdapters = @extended ConsoleWrite("# of Adapters: "&$nAdapters&@CRLF) For $i = 0 To $nAdapters - 1 ConsoleWrite("Adapter #"&$i+1&":" & _ " [0] Index #"& $aIPv4Adapters[$i][0] & _ ", [1] Type = " & $aIPv4Adapters[$i][1] & _ ", [2] DHCP Enabled Flag = " & $aIPv4Adapters[$i][2] & _ ", [3] WINS Enabled Flag = " & $aIPv4Adapters[$i][3] & _ ", [4] Physical [MAC] Address: " & $aIPv4Adapters[$i][4] & _ ", [5] (0) = " & $aIPv4Adapters[$i][5] & @CRLF & _ ", [6] Description: "& $aIPv4Adapters[$i][6] & _ ", [7] [Empty '']: " & $aIPv4Adapters[$i][7] & _ ", [8] Adapter/Service Name [GUID] = " & $aIPv4Adapters[$i][8] & _ ", [9] [Empty] = " & $aIPv4Adapters[$i][9] & _ ", [10] [Empty] = " & $aIPv4Adapters[$i][10] & @CRLF & _ ", [11] IPv4 Address(es): "& $aIPv4Adapters[$i][11] & _ ", [12] IP Address Mask(s): "& $aIPv4Adapters[$i][12] & @CRLF & _ ", [13] Gateway IPv4 Address(es): "& $aIPv4Adapters[$i][13] & _ ", [14] Gateway Address Mask(s) : "& $aIPv4Adapters[$i][14] & @CRLF & _ ", [15] DHCP IPv4 Address(es) = " & $aIPv4Adapters[$i][15] & _ ", [16] DHCP Address Mask(s) = " & $aIPv4Adapters[$i][16] & _ ", [17] DHCP LeaseObtained Time = " & $aIPv4Adapters[$i][17] & _ ", [18] DHCP LeaseExpires Time = " & $aIPv4Adapters[$i][18] & @CRLF & _ ", [19] Primary WINS Server IP = " & $aIPv4Adapters[$i][19] & _ ", [20] Primary WINS Server Address Mask = " & $aIPv4Adapters[$i][20] & _ ", [21] Secondary WINS Server IP(s) = " & $aIPv4Adapters[$i][21] & _ ", [22] Secondary WINS Server Address Mask(s) = " & $aIPv4Adapters[$i][22] & @CRLF) ConsoleWrite($sSeparator & @CRLF) Next ; IPv4 Interface Info alt #2 $aIPv4AddrTable = _Network_IPv4AddressTable() $nInterfaces = @extended ConsoleWrite(@CRLF) For $i = 0 To $nInterfaces - 1 ConsoleWrite("Adapter #"&$i+1&": [0] Interface Index # = " & $aIPv4AddrTable[$i][0] & _ ", [1] IPv4 Address = " & $aIPv4AddrTable[$i][1] & _ ", [2] Subnet Mask = " & $aIPv4AddrTable[$i][2] & _ ", [3] Broadcast Address = " & $aIPv4AddrTable[$i][3] & @CRLF & _ " [4] Max Reassembly Size = " & $aIPv4AddrTable[$i][4] & _ ", [5] Address Type/State = " & $aIPv4AddrTable[$i][5] & @CRLF) Next ConsoleWrite($sSeparator & @CRLF) ; IPv4 and IPv6 Interface Info (includes everything except Address Masks) ; params: 0 (IPv4 AND IPv6), 0 (don't get all IP's), 0 (don't include down-status interfaces) $aIPAllAddrTable = _Network_IPAllAddressTable(0, 0, 0) $nInterfaces = @extended ConsoleWrite($sSeparator & @CRLF) For $i = 0 To $nInterfaces - 1 ConsoleWrite("Interface #"&$i+1&": [0] Index #"& $aIPAllAddrTable[$i][0] & _ ", [1] Type = " & $aIPAllAddrTable[$i][1] & _ ", [2] Operational Status = " & $aIPAllAddrTable[$i][2] & _ ", [3] Flags = 0x" & Hex($aIPAllAddrTable[$i][3], 8) & _ ", [4] Physical [MAC] Address: " & $aIPAllAddrTable[$i][4] & _ ", [5] MTU = " & $aIPAllAddrTable[$i][5] & @CRLF & _ ", [6] Description: "& $aIPAllAddrTable[$i][6] & _ ", [7] Friendly Name: " & $aIPAllAddrTable[$i][7] & _ ", [8] Adapter/Service Name [GUID] = " & $aIPAllAddrTable[$i][8] & @CRLF & _ ", [9] Max Receive Speed [Vista+] = " & $aIPAllAddrTable[$i][9] & _ ", [10] Max Transmit Speed [Vista+] = " & $aIPAllAddrTable[$i][10] & @CRLF & _ ", [11] IPv4 Address(es): "& $aIPAllAddrTable[$i][11] & _ ", [12] IPv6 Address(es): "& $aIPAllAddrTable[$i][12] & @CRLF & _ ", [13] DNS IPv4 Address(es): "& $aIPAllAddrTable[$i][13] & _ ", [14] DNS IPv6 Address(es): "& $aIPAllAddrTable[$i][14] & @CRLF & _ ", [15] Gateway IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][15] & _ ", [16] Gateway IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][16] & @CRLF & _ ", [17] DHCP IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][17] & _ ", [18] DHCP IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][18] & @CRLF & _ ", [19] WINS IPv4 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][19] & _ ", [20] WINS IPv6 Address(es) [Vista+]: "& $aIPAllAddrTable[$i][20] & @CRLF & _ ", [21] Connection Type [Vista+] = " & $aIPAllAddrTable[$i][21] & _ ", [22] Tunnel Type [Vista+] = " & $aIPAllAddrTable[$i][22] & @CRLF) ; Interface Statistics & Info for Given index $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPAllAddrTable[$i][0]) ;~ ConsoleWrite("_Network_InterfaceEntryInfo return, @error = " & @error & ", @extended = " & @extended & @CRLF) ConsoleWrite("Interface #"&$i+1&" Entry Info: [0] Interface Index = " & $aNIEntryInfo[0] & _ ", [1] Interface Type = " & $aNIEntryInfo[1] & _ ", [2] Operational Status = " & $aNIEntryInfo[2] & _ ", [3] Admin Status = " & $aNIEntryInfo[3] & _ ", [4] Physical Address = " & $aNIEntryInfo[4] & _ ", [5] MTU [Max Trans. Unit] in bytes = " & $aNIEntryInfo[5] & @CRLF & _ ", [6] Description = " & $aNIEntryInfo[6] & _ ", [7] Interface Name = " & $aNIEntryInfo[7] & @CRLF & _ ", [8] Last change [1/100th second] = " & $aNIEntryInfo[8] & _ ", [9] Interface Speed [bps] = " & $aNIEntryInfo[9] & @CRLF & _ ", [10] # Recvd Data [in Octets] = " & $aNIEntryInfo[10] & _ ", [11] # Recvd Unicast Packets = " & $aNIEntryInfo[11] & _ ", [12] # Recvd Non-Unicast Packets = " & $aNIEntryInfo[12] & _ ", [13] # Recvd Packets Discarded [no error] = " & $aNIEntryInfo[13] & _ ", [14] # Recvd Packets Discarded [error] = " & $aNIEntryInfo[14] & _ ", [15] # Recvd Packets Discarded [unk. protocol] = " & $aNIEntryInfo[15] & @CRLF & _ ", [16] # Sent Data [in Octets] = " & $aNIEntryInfo[16] & _ ", [17] # Sent Unicast Packets = " & $aNIEntryInfo[17] & _ ", [18] # Sent Non-Unicast Packets = " & $aNIEntryInfo[18] & _ ", [19] # Sent Packets Discarded [no error] = " & $aNIEntryInfo[19] & _ ", [20] # Sent Packets Discarded [error] = " & $aNIEntryInfo[20] & @CRLF & _ ", [21] Transmit Queue Length [n/a] = " & $aNIEntryInfo[21] & @CRLF) ConsoleWrite($sSeparator & @CRLF) Next $hSplash=SplashTextOn("Network Usage Information", "", 520, 24 + (19 * 15) + ($nInterfaces * (5.5 * 15)), Default, Default, 16+4, "Lucida Console", 11) ; Start loop Do $aIPStats = _Network_IPStatistics() $aTCPStats = _Network_TCPStatistics() $aUDPStats = _Network_UDPStatistics() $aICMPStats = _Network_ICMPStatistics() $aIPv6Stats = _Network_IPStatistics(1) $aTCPv6Stats = _Network_TCPStatistics(1) $aUDPv6Stats = _Network_UDPStatistics(1) $aICMPv6Stats = _Network_ICMPStatistics(1) $sSplashText = StringFormat("%35s", "== TCP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Segments] Recvd = %10u | Sent = %10u", $aTCPStats[9], $aTCPStats[10]) & @CRLF $sSplashText &= StringFormat("IPv6: [Segments] Recvd = %10u | Sent = %10u", $aTCPv6Stats[9], $aTCPv6Stats[10]) & @CRLF $sSplashText &= StringFormat("<Total Connections> IPv4: %10u | IPv6: %10u", $aTCPStats[14], $aTCPv6Stats[14]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== UDP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Datagrams] Recvd = %10u | Sent = %10u", $aUDPStats[0], $aUDPStats[3]) & @CRLF $sSplashText &= StringFormat("IPv6: [Datagrams] Recvd = %10u | Sent = %10u", $aUDPv6Stats[0], $aUDPv6Stats[3]) & @CRLF $sSplashText &= StringFormat("<Total Listeners> IPv4: %10u | IPv6: %10u", $aUDPStats[4], $aUDPv6Stats[4]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== IP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Datagrams] Recvd = %10u | Sent = %10u", $aIPStats[2], $aIPStats[9]) & @CRLF $sSplashText &= StringFormat("IPv6: [Datagrams] Recvd = %10u | Sent = %10u", $aIPv6Stats[2], $aIPv6Stats[9]) & @CRLF $sSplashText &= @CRLF & StringFormat("%35s", "== ICMP Stats ==") & @CRLF $sSplashText &= StringFormat("IPv4: [Messages] Recvd = %10u | Sent = %10u", $aICMPStats[0], $aICMPStats[2]) & @CRLF $sSplashText &= StringFormat("IPv6: [Messages] Recvd = %10u | Sent = %10u", $aICMPv6Stats[0], $aICMPv6Stats[2]) & @CRLF For $i = 0 To $nInterfaces - 1 ;~ $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPv4AddrTable[$i][0]) ;~ $sSplashText &= @CRLF & StringFormat("%35s", "== IP " & $aIPv4AddrTable[$i][1] & " ==" ) & @CRLF $aNIEntryInfo = _Network_InterfaceEntryInfo($aIPAllAddrTable[$i][0]) If @error Then ConsoleWrite("_Network_InterfaceEntryInfo return, @error = " & @error & ", @extended = " & @extended & @CRLF) ExitLoop EndIf If $aIPAllAddrTable[$i][11] <> "" Then $sSplashText &= @CRLF & StringFormat("%40s", "== IPv4 " & $aIPAllAddrTable[$i][11] & " ==" ) & @CRLF Else $sSplashText &= @CRLF & StringFormat("%52s", "== IPv6 " & $aIPAllAddrTable[$i][12] & " ==" ) & @CRLF EndIf $sSplashText &= StringFormat("%45.56s", $aNIEntryInfo[6]) & @CRLF ; Octet *should* be the same as Bytes.. $sSplashText &= StringFormat("Data (Octets/Bytes): Recvd = %10u | Sent = %10u", $aNIEntryInfo[10], $aNIEntryInfo[16]) & @CRLF $sSplashText &= StringFormat("Unicast Packets: Recvd = %10u | Sent = %10u", $aNIEntryInfo[11], $aNIEntryInfo[17]) & @CRLF $sSplashText &= StringFormat("Non-Unicast Packets: Recvd = %10u | Sent = %10u", $aNIEntryInfo[12], $aNIEntryInfo[18]) & @CRLF Next $sSplashText &= @CRLF & StringFormat("%35s", "[ESC] Exits") & @CRLF ControlSetText($hSplash, "", "[CLASS:Static; INSTANCE:1]", $sSplashText) Sleep(500) Until $bHotKeyPressed NetworkStatistics.zip ~prev version. downloads: >100 Updates: 2013-07-11: Changed: _Network_IPv4AdaptersInfoEx() now returns all IP's (if requested) and Address Masks Fixed: WSALastError call possible crash with non-array variable Changed: _Network_IPAllAddressTable() now allows 'down' status interfaces to be returned Added: Some comments on development, info on getting additional stats in the UDF 2013-07-06: Added: Much more Adapter Information Changed: Example is now separate from the UDF Fixed some minor issues here and there Changed: Global Handle to IPHLPAPI.DLL is now contained in the UDF and used to speed up function calls Misc. Other fixes I didn't keep track of! 2013-07-02: Hotfix: Ipv6 indexing error Fixed: indexing, updated and enhanced output Changed: Various functions return arrays even if failure - this is to make XP pre-SP1 and also collection of IPv6 less troublesome. @error should still be checked on return though! Added: Adapter and Interface information and statistics collection 2013-06-20: Now covers all the 'p's - IP and ICMP now added
  15. Hello, I just made another TCP server. I will use the server for data collection and a lot of clients can get the data from TCP. I now use it for UDP broadcast some devices to get their IP's. You can also use it for chat's. It is very low level, but so you have more options than with the pure AutoIt functions. Just start the server in SciTE to see the console outputs. Then you can start up to 63 clients to talk to the server. I hope you like it. Server script: #include "socket_UDF.au3" ;funkey 2013.06.21 _WSAStartup() Global $iSocket Global $iReturn Global $iPort = 20500 Global $sIP_Connected Global $iPort_Connected Global $tBuffer = DllStructCreate("char buffer[512]") $iSocket = _socket($AF_INET, $SOCK_STREAM, $IPPROTO_TCP) ConsoleWrite("Listen Socket: " & $iSocket & @CRLF) Global $tReUse = DllStructCreate("BOOLEAN reuse") DllStructSetData($tReUse, "reuse", True) ; enable reusing the same port $iReturn = _setsockopt($iSocket, $SOL_SOCKET, $SO_REUSEADDR, $tReUse) ; set reusing option for the port If $iReturn Then ConsoleWrite("SetSockOpt error setting reusing the same port!. Windows Sockets Error Codes: " & _WSAGetLastError() & @CRLF) EndIf $iReturn = _bind($iSocket, @IPAddress1, $iPort) ;local IP-Address and port to use If $iReturn Then ConsoleWrite("Bind error: " & $iReturn & @CRLF) ; 0 is OK EndIf $iReturn = _listen($iSocket, 1) If $iReturn Then ConsoleWrite("Listen error: " & $iReturn & @CRLF) ; 0 is OK EndIf Global $iNewSocket Global $tReadFds = DllStructCreate($tagFd_set) Global $tReadFds_Copy = DllStructCreate($tagFd_set) _FD_ZERO($tReadFds) _FD_SET($iSocket, $tReadFds) Global $iSocketMax = $iSocket Global $iSocketNow Global $sDataRcv While 1 DllCall('ntdll.dll', 'none', 'RtlMoveMemory', 'struct*', $tReadFds_Copy, 'struct*', $tReadFds, 'ULONG_PTR', DllStructGetSize($tReadFds)) $iReturn = _select($iSocketMax + 1, $tReadFds_Copy, 2000) ;timeout 2 seconds If _FD_ISSET($iSocket, $tReadFds_Copy) Then $iNewSocket = _accept($iSocket, $sIP_Connected, $iPort_Connected) _FD_SET($iNewSocket, $tReadFds) _FD_SHOW($tReadFds) If $iNewSocket > $iSocketMax Then $iSocketMax = $iNewSocket ConsoleWrite("New connected socket: " & $iNewSocket & @TAB & "IP: " & $sIP_Connected & @TAB & "Port: " & $iPort_Connected & @LF) EndIf For $i = 2 To DllStructGetData($tReadFds, "fd_count") $iSocketNow = DllStructGetData($tReadFds, "fd_array", $i) If _FD_ISSET($iSocketNow, $tReadFds_Copy) Then DllCall('ntdll.dll', 'none', 'RtlZeroMemory', 'struct*', $tBuffer, 'ULONG_PTR', DllStructGetSize($tBuffer)) If _recv($iSocketNow, $tBuffer) = $SOCKET_ERROR Then _closesocket($iSocketNow) _FD_CLR($iSocketNow, $tReadFds) Else $sDataRcv = DllStructGetData($tBuffer, 1) ConsoleWrite("Data received: " & $sDataRcv & @LF) If $sDataRcv == "CloseServer!" Then ExitLoop 2 EndIf EndIf EndIf Next WEnd For $i = 1 To DllStructGetData($tReadFds, "fd_count") _closesocket(DllStructGetData($tReadFds, "fd_array", $i)) Next _WSACleanup() Func _FD_SHOW(ByRef $tFd_set) For $i = 1 To DllStructGetData($tFd_set, "fd_count") ConsoleWrite($i & ":" & @TAB & DllStructGetData($tFd_set, "fd_array", $i) & @LF) Next EndFunc ;==>_FD_SHOWsocket_UDF and example.rar
  16. Hi I have an idea of creating a parental filter (freeware) , which will be protecting children from navigating to adult websites. I want to ask, what is your opinion, how to do it best way? How to catch the traffic from the very beginning? For example if a user is starting IE or Firefox, or if he has some alternate BLABLA-browser - how can I catch the url before actual navigation to website, so that my script could first check if the website is ok, and then if it decides that the website is not ok, just block connection to this IP. Looking forward to your opinions, Great thanx in advance!
  17. Hello everyone. I'm wondering if its possible: I want to try create a simple autoit script that will 1) first he must connect to some IP in internet port 80 2) then he must listen for incoming connections from other IP'S ports 8000 - 8200 [in total over 200 connections] 3) that script must send all recieved data from that [IP in internet port 80 ] to [other IP'S ports 8000 - 8200] is that very hard to do ? Any suggestions or maybe some similar examples that can help me to do this ? all those 200 connections must receive data at the same time at once is it possible to do so ?
  18. 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) 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 ?
  19. I am working on a desktop remote application so I made a simple server and client to send binary screen captures from client to server. All it's good if I test both scripts on my computer but when the client is in other network many screen shots are corrupted and some of them looks good. Have any idea why? Client: #include <ScreenCapture.au3> #include <Memory.au3> #include <WinAPI.au3> #include <GDIPlus.au3> TCPStartup() $Client = TCPConnect(@IPAddress1,12100) _GDIPlus_Startup() While True Local $hHBitmap = _ScreenCapture_Capture('') Local $hBitmap = _GDIPlus_BitmapCreateFromHBITMAP($hHBitmap) $bData = _GDIPlus_StreamImage2BinaryString($hBitmap) _GDIPlus_BitmapDispose($hBitmap) _WinAPI_DeleteObject($hHBitmap) TCPSend($Client,'~stream:' & BinaryLen($bData)) While BinaryLen($bData) $a = TCPSend($Client, $bData) $bData = BinaryMid($bData, $a+1, BinaryLen($bData)-$a) WEnd Sleep(10) WEnd TCPCloseSocket($Client) TCPShutdown() _GDIPlus_Shutdown() Func _GDIPlus_StreamImage2BinaryString($hBitmap, $sFormat = "JPG", $iQuality = 100) ;UEZ Local $sImgCLSID, $tGUID, $tParams, $tData Switch $sFormat Case "JPG" $sImgCLSID = _GDIPlus_EncodersGetCLSID($sFormat) $tGUID = _WinAPI_GUIDFromString($sImgCLSID) $tData = DllStructCreate("int Quality") DllStructSetData($tData, "Quality", $iQuality) ;quality 0-100 Local $pData = DllStructGetPtr($tData) $tParams = _GDIPlus_ParamInit(1) _GDIPlus_ParamAdd($tParams, $GDIP_EPGQUALITY, 1, $GDIP_EPTLONG, $pData) Case "PNG", "BMP", "GIF", "TIF" $sImgCLSID = _GDIPlus_EncodersGetCLSID($sFormat) $tGUID = _WinAPI_GUIDFromString($sImgCLSID) Case Else Return SetError(1, 0, 0) EndSwitch Local $hStream = _WinAPI_CreateStreamOnHGlobal() ;http://msdn.microsoft.com/en-us/library/ms864401.aspx If @error Then Return SetError(2, 0, 0) _GDIPlus_ImageSaveToStream($hBitmap, $hStream, DllStructGetPtr($tGUID), DllStructGetPtr($tParams)) If @error Then Return SetError(3, 0, 0) Local $hMemory = _WinAPI_GetHGlobalFromStream($hStream) ;http://msdn.microsoft.com/en-us/library/aa911736.aspx If @error Then Return SetError(4, 0, 0) Local $iMemSize = _MemGlobalSize($hMemory) If Not $iMemSize Then Return SetError(5, 0, 0) Local $pMem = _MemGlobalLock($hMemory) $tData = DllStructCreate("byte[" & $iMemSize & "]", $pMem) Local $bData = DllStructGetData($tData, 1) _WinAPI_ReleaseStream($hStream) ;http://msdn.microsoft.com/en-us/library/windows/desktop/ms221473(v=vs.85).aspx _MemGlobalFree($hMemory) Return $bData EndFunc ;==>_GDIPlus_StreamImage2BinaryString Server Global $Buffer, $BufferSize Global $Count = 0 TCPStartup() $Server = TCPListen(@IPAddress1,12100) If @error Then MsgBox(0,'',@error) Do $Socket = TCPAccept($Server) Sleep(10) Until $Socket <> -1 While True $Recv = TCPRecv($Socket,10240) If $Recv = -1 Then ExitLoop ElseIf $Recv Then If StringLeft($Recv,7) = '~stream' Then $BufferSize = StringSplit($Recv,':')[2] $Buffer = '0x' Do $Recv = TCPRecv($Socket,10240) If BinaryLen($Recv) <> 0 Then $BufferSize -= BinaryLen($Recv) $Buffer &= StringTrimLeft($Recv,2) EndIf Until $BufferSize = 0 $hFile = FileOpen(@ScriptDir & '\Screen' & $Count & '.jpeg',18) FileWrite($hFile,$Buffer) FileClose($hFile) $Buffer = Null $Count += 1 EndIf If $Count = 100 Then ExitLoop EndIf Sleep(10) WEnd TCPCloseSocket($Socket) TCPCloseSocket($Server) TCPShutdown() Exit
  20. 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: 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
  21. Hi! If you liked my TCPServer UDF, you'll also like this one. Following the same principles, this TCPClient UDF helps you on handling multiple connections to different servers, and set actions depending on two events: OnReceive and OnDisconnect. It is also multi server (you can connect to many servers at once) and you can also bind a Console-based executable to the socket (similar to -e parameter in NetCat). This feature is useful if you want to use some Console UDF to create a TCP application and don't want to deal with the TCP* functions. Also, it runs on background just firing events, it won't pause your script while waiting/receiving data, so you can do anything else (close and open connections, allow the user to click buttons or just wait on an infinite loop) that your callbacks will be called once the event is fired It is also very easy to use. See this examples: Example #1: Connecting to a basic server By running this (as soon as you open a basic server with Netcat) you will receive a message box telling you when the server closes the connection (the socket ID and his IP address are passed as parameter to your callback function) and also when the server sends something over the TCP socket (the data sent is passed as parameter). #cs Download netcat at https://eternallybored.org/misc/netcat/ Execute this script Run in CMD: nc -vv -l -p 8081 #ce #include "TCPClient.au3" ; First we set the callback functions for the two events (none of them is mandatory) _TCPClient_OnDisconnect("disconnect") _TCPClient_OnReceive("received") ; And a parameter _TCPClient_DebugMode(True) ; Finally we connect to the server at port 8081 at any interface _TCPClient_Connect('127.0.0.1', 8081) Func disconnect($iSocket, $sIP) MsgBox(0, "Server disconnected", "Server " & $sIP & " disconnected from socket " & $iSocket) EndFunc ;==>disconnect Func received($iSocket, $sIP, $sData, $sPar) MsgBox(0, "Data received from " & $sIP, $sData & @CRLF & "Parameter: " & $sPar) _TCPClient_Send($iSocket, "You wrote: " & $sData) _TCPClient_SetParam($iSocket, 'will write again') EndFunc ;==>received While 1 Sleep(100) WEndExample #2: Requesting a page from a HTTP server In this example, we run this code and it will get the response from a HTTP server. Of course, as we are requesting google.com index, it may just show a redirect page to a local (with country top-level domain) Google page or with some stuff on the URL. #include "TCPClient.au3" _TCPClient_OnReceive("received") _TCPClient_DebugMode(True) $iSocket = _TCPClient_Connect(TCPNameToIP('google.com'), 80) If @error Then Exit _TCPClient_Send($iSocket, "GET / HTTP/1.0" & @CRLF & @CRLF) Func received($iSocket, $sIP, $sData, $sParam) MsgBox(0, "Data received", $sData) _TCPClient_Disconnect($iSocket) EndFunc ;==>received While 1 Sleep(100) WEndExample #3: Command prompt bound to the socket after password requesting By running this example, we will be asked for a password, which is 123456 as we set on the script. If the password is correct, we will see the Command Prompt live-updated (try running a ping to some server, for example). #include "TCPClient.au3" #cs To test this example, execute a netcat server, running this commands: nc -vv -l -p 31337 #ce Global $Password = "123456" _TCPClient_OnReceive("receive") _TCPClient_OnDisconnect("disconnect") _TCPClient_DebugMode() Func receive($iSocket, $sIP, $sData, $mPar) If $mPar = "login" Then If $sData = $Password Then ; right password, let's change the parameter _TCPClient_SetParam($iSocket, "logged") ; and now bind _TCPClient_BindAppToSocket($iSocket, "cmd.exe") Else _TCPClient_Send($iSocket, "Wrong password. Try again: ") EndIf Else If $sData = "exit" Then ; unbinds _TCPClient_UnBindAppToSocket($iSocket) ; says bye _TCPClient_Send($iSocket, "See you") ; closes connection _TCPClient_Disconnect($iSocket) Else ; sends command directly to the process _TCPClient_SendToBound($iSocket, $sData) EndIf EndIf EndFunc Func disconnect($iSocket, $sIP) MsgBox(0, $iSocket, $sIP) EndFunc $iSocket = _TCPClient_Connect('127.0.0.1', '31337') If @error Then MsgBox(0, "", "could not connect. Error: " & @error) Exit EndIf ; Sets parameter to login, so we know what the server is doing _TCPClient_SetParam($iSocket, "login") _TCPClient_Send($iSocket, "Please enter password: ") While True Sleep(100) WEndThe limit is your imagination? Well, maybe. Functions list: _TCPClient_Connect($sSvr, $iPort) _TCPClient_Disconnect($iSocket) _TCPClient_SetParam($iSocket, $sPar) _TCPClient_Send($iSocket, $sData) _TCPClient_Broadcast($sData [, $iExceptSocket = 0 ]) _TCPClient_ListConnections() _TCPClient_BindAppToSocket($iSocket, $sCommand [, $sWorkingDir = @WorkingDir ]) _TCPClient_SendToBound($iSocket, $sData) _TCPClient_UnBindAppToSocket($iSocket) _TCPClient_OnReceive($sCallback) _TCPClient_OnDisconnect($sCallback) _TCPClient_DebugMode([ $bMOde = "toggle" ]) _TCPClient_AutoTrim([ $bMode = "toggle" ]) _TCPClient_SocketToConnID($iSocket) _TCPClient_ConnIDToSocket($iConn) _TCPClient_SocketToIP($iSocket)Help file and more examples included! Latest version: 1.0.0 Download: https://www.autoitscript.com/forum/files/file/377-tcpclient-udf/ Changelog 1.0.0 - First release - 03/12/2015If you can't open the help file, please uncompress it, go to properties and click Unlock. Fork me on Github: http://github.com/jesobreira/tcpclient-udf
  22. Hi, How can i use a external function in TCPSend / TCPRecv , It's meant : TCPSend ( $main, function1 ) func function1 () msgbox (0,0,0) endfunc Q : Why i need to use that ? A : I need when a connection was true ( connected ) , server could send some functions and client receive that, Me => <= You Thanks
  23. Hello, I have a problem, I downloaded example of TCP Server and Client, but client doesn't work, It shows TCPConnect 10060 error (timeout), I tried to turn on two servers, I think server work, because one server show 10048 error(Address already in use) I don't know why it doesn't work, I edited that script, but it doesn't work still. I tried TCPConnect and TCPAccept from AutoIt3\Examples\Helpfile, but TCPConnect shows error 10060(timeout)... Anybody knows how to fix it? Thanks ; SERVER #include <Array.au3> TCPStartup() Dim $Socket_Data[1] $Socket_Data[0] = 0 $Listen = TCPListen(@IPAddress1, 1018, 500) If @error Then ConsoleWrite('!-->['&@Hour&":"&@MIN&":"&@SEC&'] TCPListen error. ( ' & @error & ' )' & @CRLF) Exit EndIf While 1 For $x = $Socket_Data[0] To 1 Step -1 $Recv = TCPRecv($Socket_Data[$x], 1000000) If $Recv Then MsgBox(0, 'Client Number ' & $x & ' with connected socket identifier ' & $Socket_Data[$x], "["&@Hour&":"&@MIN&":"&@SEC&"]"&' Recived msg from Client: ' & @CRLF & $Recv, 5) TCPSend($Socket_Data[$x], 'bye') TCPCloseSocket($Socket_Data[$x]) _ArrayDelete($Socket_Data, $x) $Socket_Data[0] -= 1 EndIf Next _Accept() WEnd Func _Accept() Local $Accept = TCPAccept($Listen) If $Accept <> -1 Then _ArrayAdd($Socket_Data, $Accept) $Socket_Data[0] += 1 EndIf EndFunc ;==>_Accept exit; CLIENT $Connected = False TCPStartup() ; Start TCP. $timespentconnecting = TimerInit( ) Do $Socket = TCPConnect(@IPAddress1, 1018) ; Connect to server. $nERROR = @error ; TCPConnect @error. If not $nERROR Then ; If client connected to server. $Connected = True Else ; If TCPConnect didn't connected to server. ConsoleWrite( "["&@Hour&":"&@MIN&":"&@SEC&"] TCPConnect error. {CODE:" & $nERROR & "}"&@CRLF ) ; Show error. EndIf sleep(100) ; Sleep 0.1 secounds. Until $Connected = True or TimerDiff( $timespentconnecting ) > 10000 ; If client connected or timer > 10 secounds, stop trying connect to server. If $Connected = False then exit ; If client didn't connected to server, exit. TCPSend($Socket, 'Hi there. My computer name is' & ", " & @ComputerName & ", and its drive serial is " & DriveGetSerial(@HomeDrive)); Send to server data. Do ; Loop until client recives data from server. $Recv = TCPRecv($Socket, 1000000) ; Recive data from server. Until $Recv ; Stop looping when data recived from server. MsgBox(0, "["&@Hour&":"&@MIN&":"&@SEC&"] Recived from server:", $Recv); Show recived data from server. Exit(0) ; Exit.
  24. Morning all, For past few days I've been rattling my brains trying to work out how to create TCP Server and Client. I have successfully made a connection between a single client and server but beyond that I'm hopeless! I've been messing with Arrays and trying to read other examples but it's a little over my head... I was hoping I could ask someone to give me a really simple example with some comments for a server to accept multiple connections and a client to connect and receive data from server. I'm planning to have a client and server GUI to display "Client connected with identifier" "Server connected" "Message from server" etc Thanks in advance!
  25. Hello, I'm trying my hand at a simple TCP server and client but I have a bit of a worry! I create a simple GUI to return the error code following the TCPStartUp command and its returning an error! I have tried using some example TCP Scripts too which don't seem to work properly. Would someone mind having a look at my code below and tell me if the TCPStartUp should be working? Should it be returning errorcode 1? And should my text steps be TCP Listen > TCP Accept > TCP Recieve? I'm a bit of a noob so any help would be hugely appreciated #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('GUIonEventMode', 1) $GUI = GUICreate("S.M.I Server", 472, 311, 751, 312) $Content = GUICtrlCreateEdit("", 8, 8, 313, 289, BitOR($GUI_SS_DEFAULT_EDIT,$ES_READONLY)) GUISetState(@SW_SHOW) GUICtrlSetData($Content, "Content") TCPStartup() IF @error == 1 Then GUICtrlSetData($content, "TCP Services started with: " & @Error) Else GUICtrlSetData($content, "TCP Services failed with error: " & @error) EndIf While 1 GUISetOnEvent($GUI_EVENT_CLOSE, "quit", $GUI) WEnd Func quit() TCPShutdown() GUICtrlSetData($content, "TCP Shut Down: " & @error) sleep(700) Exit EndFunc