|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Autoit en español
Aplicaciones con Autoit - Juan Antonio Villalpando

-- Tutorial de iniciación a Autoit --

Volver al índice del tutorial

____________________________

119B.- Apagar el ordenador por WiFi. Arrancar el Bloc de notas. TCPServerUDF.

p119B_WiFiAutoit.aia

De https://www.autoitscript.com/forum/topic/169774-tcpserver-udf-multi-client-event-based-able-to-bind-console-app-to-socket

https://github.com/jesobreira/TCPServerUDF

TCPServer UDF.rar

8_hibernar_run_msgbox.htm

- El archivo TCPServer.au3 es el servidor, debe estar en el mismo directorio que los demás ejemplos.

- Este es el ejemplo del autor, he modificado un poco el código, cuando recibe "notepad" se abre el Bloc de notas. Cuando recibe "shutdown" se apaga el ordenador.

- No ofrece retorno de información.

example.au3

#include "TCPServer.au3"

; First we set the callback functions for the three events (none of them is mandatory)
;_TCPServer_OnConnect("connected")
;_TCPServer_OnDisconnect("disconnect")
_TCPServer_OnReceive("received")


; And some parameters
_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

; Finally we start the server at port 8081 at any interface
_TCPServer_Start(8081)

Func connected($iSocket, $sIP)
	MsgBox(0, "Client connected", "Client " & $sIP & " connected!")
	_TCPServer_Broadcast('new client connected guys', $iSocket)
	_TCPServer_Send($iSocket, "Hey! Write something ;)" & @CRLF)
	_TCPServer_SetParam($iSocket, "will write")
EndFunc   ;==>connected

Func disconnect($iSocket, $sIP)
	MsgBox(0, "Client disconnected", "Client " & $sIP & " disconnected from socket " & $iSocket)
EndFunc   ;==>disconnect

Func received($iSocket, $sIP, $sData, $sPar)
	  MsgBox(0, "Data received from " & $sIP, $sData & @CRLF & "Parameter: " & $sPar)
	 ;_TCPServer_Send($iSocket, "You wrote: " & $sData)
	 ;_TCPServer_SetParam($iSocket, 'will write again')
	       $iPosition = StringInStr($sData, "notepad")
		   if $iPosition <> 0 Then
              Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		   EndIf
	       $iPosition = StringInStr($sData, "shutdown")
		   if $iPosition <> 0 Then
             Shutdown(64)
		   EndIf
EndFunc   ;==>received

While 1
	Sleep(100)
WEnd

_________________
- Diseño.

_________________
- Bloques.

_____________________________

2.- Código mejorado. Retorno de información.

- Este código es más simple y además retorna información al bloque Web.GotText.

- Además cierra la conexión cada vez que se ejecuta para no dejar el socket abierto.

example_return.au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)

Func received($iSocket, $sIP, $sData, $sParam)
      $iPosition = StringInStr($sData, "notepad")
		   if $iPosition <> 0 Then
              Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		   EndIf

	  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
					"Content-Type: text/html" & @CRLF & @CRLF & _
					"Notepad running.")
	_TCPServer_Close($iSocket)
EndFunc   ;==>received

While 1
	Sleep(100)
WEnd

 

_____________________________

3.- Ejecutar y cerrar el Bloc de notas.

- Mediante taskkill cerramos el Bloc de notas (notepad.exe)

example_kill.au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)

Func received($iSocket, $sIP, $sData, $sParam)
	   $iPosition = StringInStr($sData, "notepad")
	   if $iPosition <> 0 Then
		  Run("notepad.exe", "", @SW_SHOWMAXIMIZED)
		  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Notepad running.")
	     _TCPServer_Close($iSocket)
	   EndIf

	   $iPosition = StringInStr($sData, "kill")
	   if $iPosition <> 0 Then
		   Run(@ComSpec & " /c " & 'taskkill /IM "notepad.exe" /F', "", @SW_HIDE)
		  _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Killing Notepad.")
	     _TCPServer_Close($iSocket)
	   EndIf


EndFunc   ;==>received

_____________________________

4.- Subir archivo desde la App al ordenador.

p119B_WiFiAutoit_Archivo.aia

- Mediante la extensión KIO4_Base64 convertimos un archivo de imagen a string en Base64.

- Subimos ese string al ordenador mediante el script.

- Decodificamos el string y lo guardarmos en un archivo.

- El archivo siempre se llama, en este ejemplo, imagen1.png, se puede modificar el código para que tenga el nombre real del archivo.

- El código contiene dos ejemplos:

a) Copia el archivo foto5.png desde el asset al ASD.

Lo convierte a Base64 mediante la extensión y lo sube al ordenador mediante el script.

b) Hace una foto con la cámara, muestra la dirección donde está la foto.

Lo convierte a Base64 mediante la extensión y lo sube al ordenador mediante el script.

_________________
- Bloques.

_________________
- Bloques.

_________________
- Código.

- En el mismo directorio debe estar el TCPServer.au3

archivo.au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)


Func received($iSocket, $sIP, $sData, $sPar)

Sleep(100)
$BASE64_DATA = $sData
$BASE64_DATA = StringReplace ($BASE64_DATA, @CR, "")
$BASE64_DATA = StringReplace ($BASE64_DATA, @LF, "")

$base64_code =  StringSplit($BASE64_DATA, "gzip", 1)
$BASE64_DATA =$base64_code[2]

    Local $hFile = 0
	$sImageName = "imagen1.png"
    $hFile=FileOpen($sImageName, 18)
    FileWrite($hFile, _Encoding_Base64Decode($BASE64_DATA))
    FileClose($hFile)

    _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				"Recibido.")
	     _TCPServer_Close($iSocket)

EndFunc   ;==>received

While 1
	Sleep(100)
WEnd


Func _Encoding_Base64Decode($sData)
    Local $struct = DllStructCreate("int")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $sData, _
            "int", 0, _
            "int", 1, _
            "ptr", 0, _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(1, 0, "") ; error calculating the length of the buffer needed
    EndIf

    Local $a = DllStructCreate("byte[" & DllStructGetData($struct, 1) & "]")

    $a_Call = DllCall("Crypt32.dll", "int", "CryptStringToBinary", _
            "str", $sData, _
            "int", 0, _
            "int", 1, _
            "ptr", DllStructGetPtr($a), _
            "ptr", DllStructGetPtr($struct, 1), _
            "ptr", 0, _
            "ptr", 0)

    If @error Or Not $a_Call[0] Then
        Return SetError(2, 0, "") ; error decoding
    EndIf

    Return BinaryToString(DllStructGetData($a, 1))
EndFunc   ;==>_Encoding_Base64Decode

_____________________________

5.- Copiar archivo del ordenador a la App.

p119B_WiFiAutoit_Get_File.aia

- Escribimos la dirección absoluta de un archivo existente en el ordenador, por ejemplo: C:\Users\juan\Documents\foto6.png

- Esa dirección se enviará al Server.

- El Server tomará ese archivo, lo convertirá a Base64 y devolverá la información.

- La aplicación recibirá el string Base64 mediante el bloque Web.GotText.

- Mediante la extensión KIO4_Base64, ese string se convertirá en archivo y se guardará en el ASD.

- Se mostrará la imagen.

- IMPORTANTE: no funciona con direcciones que tengan espacios, por ejemplo esto no funcionaría: C:\Downloads\foto 6.png

_________________
-
Diseño.

_________________
- Bloques.

_________________
- Código.

- En el mismo directorio debe estar el TCPServer.au3

- El código de Base64 es de:

https://www.autoitscript.com/forum/topic/145526-base64-converter-files-and-strings-can-be-modified-easily

archivo_pasar .au3

#include "TCPServer.au3"

_TCPServer_OnReceive("received")

_TCPServer_DebugMode(True)
_TCPServer_SetMaxClients(10)

_TCPServer_Start(8081)
Global $__b64___B64_list[64]


Func received($iSocket, $sIP, $sData, $sPar)

$receive = StringSplit($sData, "gzip", 1)
$address = $receive[2]
$address = StringStripWS($address, 1) ; remove white space
$encoded = B64Encode($address, 0, 64, 1)
; MsgBox(0, 'Completed', $encoded)


    _TCPServer_Send($iSocket, "HTTP/1.0 200 OK" & @CRLF & _
				"Content-Type: text/html" & @CRLF & @CRLF & _
				 $encoded)
	_TCPServer_Close($iSocket)

EndFunc   ;==>received

While 1
	Sleep(100)
WEnd


; ======================= Functions: =========================
Func B64Encode($__b64_input = '', $__b64_mode = 0, $__b64_linebreak = 0, $__b64_isfile = 0)
If $__b64_input = '' Then MsgBox(0, 'Hint', 'B64Encode($InputData, 0 = ANSI 1 = is UTF-8, 0-76 Linebreak, 1 = is a file (filename)')
__init_b64_dictionary()
If $__b64_linebreak > 76 Then
MsgBox(0, 'Error', 'Base64 encode linebreak cannot exceed 76 characters.')
Exit
EndIf
If $__b64_mode = 0 Then
$__b64_mode = 1
Else
$__b64_mode = 4
EndIf
Local $__b64_TheBitStream, $__b64_4_SixBitChunks, $__b64_FinalOutput, $__b64_tempvalue, $__b64_FinalOutput2
If Not $__b64_isfile Then
$__b64_o_UTF_8 = StringTrimLeft(StringToBinary($__b64_input, $__b64_mode), 2)
Else
$__b64_openfile = FileOpen($__b64_input, 16)
$__b64_o_UTF_8 = StringTrimLeft(FileRead($__b64_openfile), 2)
FileClose($__b64_openfile)
EndIf
For $__b64_a = 1 To StringLen($__b64_o_UTF_8) Step 2
$__b64_TheBitStream &= __init_b64_EightBitBinary('0x' & StringMid($__b64_o_UTF_8, $__b64_a, 2))
Next
For $__b64_a = 1 To StringLen($__b64_TheBitStream) Step +6
$__b64_Number = __init_b64_FromSixBitBinary(StringMid($__b64_TheBitStream, $__b64_a, 6))
$__b64_FinalOutput &= $__b64___B64_list[$__b64_Number]
Next
While Floor(StringLen($__b64_FinalOutput) / 4) <> (StringLen($__b64_FinalOutput) / 4)
$__b64_FinalOutput &= '='
WEnd
If $__b64_linebreak > 0 Then
For $__b64_a = 1 To StringLen($__b64_FinalOutput) Step $__b64_linebreak
$__b64_FinalOutput2 &= StringMid($__b64_FinalOutput, $__b64_a, $__b64_linebreak)
If $__b64_linebreak > 0 Then
If StringLen(StringMid($__b64_FinalOutput, $__b64_a, $__b64_linebreak)) = $__b64_linebreak And $__b64_a <= (StringLen($__b64_FinalOutput) - $__b64_linebreak) Then $__b64_FinalOutput2 &= @CRLF
EndIf
Next
Else
$__b64_FinalOutput2 = $__b64_FinalOutput
EndIf
Return $__b64_FinalOutput2
EndFunc ;==>B64Encode

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_dictionary
; Description ...: Used to initialize the base64 dictionary used in conversions
; Syntax ........: __init_b64_dictionary()
; Parameters ....: None
; Return values .: None
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: Creates an array with base64 dictionary. Also creates variables with direct names for easy and quick access while decoding letters to numbers.
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_dictionary()

For $__b64_a = 0 To 63
Select
Case $__b64_a < 26
$__b64___B64_list[$__b64_a] = ChrW(65 + $__b64_a)
Assign('U' & ChrW(65 + $__b64_a), $__b64_a, 2)
Case $__b64_a < 52
$__b64___B64_list[$__b64_a] = ChrW(71 + $__b64_a)
Assign('N' & ChrW(71 + $__b64_a), $__b64_a, 2)
Case $__b64_a < 62
$__b64___B64_list[$__b64_a] = ChrW($__b64_a - 4)
Assign('N' & ChrW($__b64_a - 4), $__b64_a, 2)
Case $__b64_a = 62
$__b64___B64_list[$__b64_a] = ChrW(43)
Assign('N' & ChrW(43), $__b64_a, 2)
Case $__b64_a = 63
$__b64___B64_list[$__b64_a] = ChrW(47)
Assign('N' & ChrW(47), $__b64_a, 2)
EndSelect
Next
EndFunc ;==>__init_b64_dictionary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_EightBitBinary
; Description ...: Outputs an 8-bit binary string from an input integer between 0 and 255
; Syntax ........: __init_b64_EightBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] Integer between 0 and 255 Default is 0.
; Return values .: 8-bit binary string representing the input integer
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: An 8-bit binary string looks like 10101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_EightBitBinary($__b64_input = 0)
If $__b64_input < 256 Then
$__b64_tmpbitstream = ''
$__b64_start = 128
While $__b64_start >= 1
If Floor($__b64_input / $__b64_start) Then
$__b64_tmpbitstream &= 1
$__b64_input -= ($__b64_start * Floor($__b64_input / $__b64_start))
Else
$__b64_tmpbitstream &= 0
EndIf
$__b64_start /= 2
WEnd
Else
$__b64_tmpbitstream = 0
EndIf
Return $__b64_tmpbitstream
EndFunc ;==>__init_b64_EightBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_SixBitBinary
; Description ...: Outputs a 6-bit binary string from an input integer between 0 and 63
; Syntax ........: __init_b64_SixBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] An integer between 0 and 63. Default is 0.
; Return values .: A 6-bit binary string representing the input integer
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: A 6-bit binary string looke like 101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_SixBitBinary($__b64_input = 0)
If $__b64_input < 64 Then
$__b64_tmpbitstream = ''
$__b64_start = 32
While $__b64_start >= 1
If Floor($__b64_input / $__b64_start) Then
$__b64_tmpbitstream &= 1
$__b64_input -= ($__b64_start * Floor($__b64_input / $__b64_start))
Else
$__b64_tmpbitstream &= 0
EndIf
$__b64_start /= 2
WEnd
Else
$__b64_tmpbitstream = 0
EndIf
Return $__b64_tmpbitstream
EndFunc ;==>__init_b64_SixBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_FromSixBitBinary
; Description ...: Outputs an integer between 0 and 63 based on a 6-bit binary input.
; Syntax ........: __init_b64_FromSixBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] 6-bit binary input. Default is 0.
; Return values .: Integer between 0 and 63
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: A 6-bit binary string looke like 101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_FromSixBitBinary($__b64_input = 0)
$__b64_base = 32
$__b64_tempvalue = 0
For $__b64_a = 1 To 6
If StringMid($__b64_input, $__b64_a, 1) = 1 Then
$__b64_tempvalue += $__b64_base
EndIf
$__b64_base /= 2
Next
Return $__b64_tempvalue
EndFunc ;==>__init_b64_FromSixBitBinary

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __init_b64_FromEightBitBinary
; Description ...: Outputs an integer between 0 and 255 from an 8-bit binary input.
; Syntax ........: __init_b64_FromEightBitBinary([$__b64_input = 0])
; Parameters ....: $__b64_input - [optional] An 8-bit binary string. Default is 0
; Return values .: Integer between 0 and 255
; Author ........: Wesley G aka Morthawt
; Modified ......:
; Remarks .......: An 8-bit binary string looks like 10101010
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __init_b64_FromEightBitBinary($__b64_input = 0)
$__b64_base = 128
$__b64_tempvalue = 0
For $__b64_a = 1 To 8
If StringMid($__b64_input, $__b64_a, 1) = 1 Then
$__b64_tempvalue += $__b64_base
EndIf
$__b64_base /= 2
Next
Return $__b64_tempvalue
EndFunc ;==>__init_b64_FromEightBitBinary

_____________________________

TCPClientUDF.

- Este cliente es del mismo autor.

https://www.autoitscript.com/forum/topic/179049-tcpclient-udf-multi-client-event-based-able-to-bind-console-app-to-socket

_____

 

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información