Search the Community
Showing results for tags 'client'.
-
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
-
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
-
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.
-
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 ?
-
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
-
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!
-
Good morning, I'm hoping some of you kind people could help me get started on a simple client on a workstation which can report events and computer information back to a console on a server to display all the information. I support primary schools which are always a mess when I take them on so this would be hugely helpful. I'm still very new to AutoIT so if anyone could point me in the right direction or any examples they have would be great. I did have a quick look on the forum but the topics I found looked way more complex for my needs. Thanks
-
I'm trying to create two sides; A client side and a server side. I've got each one to work and send data from the client to the server, but if two clients are sending data at the same time. I would like to be able to get both and not just have one send while the other one gets ignored. Is there anyway I can implement a buffer so that when one connection gets done the other then starts receiving from the second client? Here is my code. ~Client Side~ TCPStartup() HotKeySet("{Esc}", "Quit") Local $ip, $port, $data, $connect $ip = "*servers IP address here*" $port = 21230 $connect = TCPConnect($ip, $port) If @error Then ConsoleWrite("Could not connect to " & $ip) sleep(1000) Quit() EndIf message() ;ConsoleWrite($data) Sleep(3000) Quit() Func message() Local $File, $Line = "", $i = 0, $EOF = "" $File = FileOpen("tcpexample.txt", 0) If $File = -1 Then MsgBox(0, "Error", "Unable to read the file.") Exit EndIf Do $Line = FileReadLine($File) $EOF = @error ConsoleWrite($Line & @CRLF) TCPSend($connect, $Line) If @error Then ConsoleWrite("There was an error sending." & @CRLF) EndIf sleep(500) Until $EOF = -1 FileClose($File) EndFunc Func Quit() TCPShutdown() Exit EndFunc ~Server Side~ TCPStartup() HotKeySet("{Esc}", "Quit") Local $ip, $port, $Accept, $Listen, $AcceptError = True, $Result $Result = FileOpen("tcptest.txt", 1) $ip = @IPAddress1;try $IPAddress2/3/4 if this doesn't work $port = 21230 $Listen = TCPListen($ip, $port) If ($listen = - 1 or $listen = 0) and (@error = 1 or @error = 2) Then ConsoleWrite("TCPListen returned @error: " & @error) Quit() EndIf While 1 If $AcceptError = True Then AcceptConnection() EndIf If $AcceptError = False Then $recv = "" $recv = TCPRecv($Accept, 1024) If @Error Then ConsoleWrite("Connection timed out: " & $Accept & @CRLF) $AcceptError = True EndIf If $recv <> "" Then FileWriteLine($Result, $recv) ConsoleWrite("We received this: " & $recv & @CRLF) EndIf EndIf WEnd Func Quit() TCPShutdown() FileClose($Result) Exit EndFunc Func AcceptConnection() $AcceptError = True While 1 $Accept = TCPAccept($Listen) If $Accept <> -1 Then ConsoleWrite($accept & " has connected" & @CRLF) $AcceptError = False ExitLoop EndIf WEnd EndFunc
-
This Function gets the Hostname of the Client on the Terminal Server, can be used to determine the correct std printer near the location of the client while working on the terminal server session. Func _GetWTSClientName($sid) Local $result = DllCall("Wtsapi32.dll", "int", "WTSQuerySessionInformation", "Ptr", 0, "int", $sid, "int", 10, "ptr*", 0, "dword*", 0) If @error Or $result[0] = 0 Then Return SetError(1, 0, "") Local $ip = DllStructGetData(DllStructCreate("byte[" & $result[5] & "]", $result[4]), 1) DllCall("Wtsapi32.dll", "int", "WTSFreeMemory", "ptr", $result[4]) Return StringReplace(BinaryToString($ip), Chr(0), "") EndFunc ;==>_GetWTSClientName Best regards, J
- 8 replies
-
- ts
- terminal server
-
(and 2 more)
Tagged with: