r2du-soft Posted May 10, 2021 Share Posted May 10, 2021 (edited) i have a java script code. that sends a parameter to the address and port and wait to return value line bye line. This process takes about 20 seconds to complete. I used the following code to convert Java code to autoit: expandcollapse popup;----------------------------------------------------- ;#includes #include-once #include <GuiConstantsEx.au3> #include <Constants.au3> #include <WindowsConstants.au3> #include <FontConstants.au3> #include <StaticConstants.au3> #include <GuiConstants.au3> #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> #include <StringConstants.au3> #include <json.au3> #include <FileConstants.au3> #include <WinAPIFiles.au3> #include <String.au3> #include <File.au3> #include <WinAPI.au3> #include <HTTP.au3> #include <Process.au3> #include <GIFAnimation.au3> #include <InetConstants.au3> #include <GuiFlatButton.au3> #include <Timers.au3> #include <Array.au3> #include "WinHttp.au3" ;---------------------------------------------------- ;----------------------------------------------------- Local $sURL_Port = "http://localhost:1401" Local $sData = '{"type":"update-db","data":{}}' ;----------------------------------------------------- ;----------------------------------------------------- ; Initialize and get session handle $hOpen = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0") ; Get connection handle $hConnect = _WinHttpConnect($hOpen, $sURL_Port) ; Make a request $hRequest = _WinHttpOpenRequest($hConnect, "Get", "") ; Send it. Specify additional data to send too. This is required by the Google API: _WinHttpSendRequest($hRequest, "Content-Type: text/json", $sData) ; Wait for the response _WinHttpReceiveResponse($hRequest) ; See what's returned Local $sReturned If _WinHttpQueryDataAvailable($hRequest) Then ; if there is data Do $sReturned &= _WinHttpReadData($hRequest) Until @error EndIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ; See what's returned MsgBox(4096, "Returned", $sReturned) ;----------------------------------------------------- But this code only returns the first line! And is unable to return and print other lines! for example java script after run return the following code: {"type": "update-db-start","data": { }} {"type": "updating-db-progress","data": {"percent":0}} {"type": "updating-db-progress","data": {"percent":1}} {"type": "updating-db-progress","data": {"percent":2}} {"type": "updating-db-progress","data": {"percent":3}} {"type": "updating-db-progress","data": {"percent":4}} {"type": "updating-db-progress","data": {"percent":5}} {"type": "updating-db-progress","data": {"percent":6}} but my autoit script just show following code: {"type": "update-db-start","data": { }} how can wait to finished and return all lines with autoit? Edited May 10, 2021 by r2du-soft Link to comment Share on other sites More sharing options...
r2du-soft Posted May 11, 2021 Author Share Posted May 11, 2021 Who has comment? i try all way but have not reached a conclusion Link to comment Share on other sites More sharing options...
Nine Posted May 11, 2021 Share Posted May 11, 2021 Try adding some sleep inside the loop ? “They did not know it was impossible, so they did it” ― Mark Twain Spoiler Block all input without UAC Save/Retrieve Images to/from Text Monitor Management (VCP commands) Tool to search in text (au3) files Date Range Picker Virtual Desktop Manager Sudoku Game 2020 Overlapped Named Pipe IPC HotString 2.0 - Hot keys with string x64 Bitwise Operations Multi-keyboards HotKeySet Recursive Array Display Fast and simple WCD IPC Multiple Folders Selector Printer Manager GIF Animation (cached) Screen Scraping Multi-Threading Made Easy Link to comment Share on other sites More sharing options...
r2du-soft Posted May 11, 2021 Author Share Posted May 11, 2021 Loop and sleep It does not change in returned value Link to comment Share on other sites More sharing options...
Danp2 Posted May 11, 2021 Share Posted May 11, 2021 Show us the working Javascript code. Otherwise, we can only guess at the reason your AutoIt translation isn't working. Latest Webdriver UDF Release Webdriver Wiki FAQs Link to comment Share on other sites More sharing options...
r2du-soft Posted May 11, 2021 Author Share Posted May 11, 2021 Thanks Danp2 this is my java script code expandcollapse popup<!DOCTYPE html> <html> <title>Websocket example</title> <body> <p id="num"></p> <body> <img src="libwebsockets.org-logo.svg"> <img src="strict-csp.svg"><br> LWS chat <b>minimal ws broker example</b>.<br> This page opens two separate ws connections...<br> A subscriber ws connection fills this textarea<br> with data it receives from the broker... <br> <br> <textarea id=r readonly cols=265 rows=30></textarea><br> <br> ... and a publisher ws connection sends the string<br> in the box below to the broker when you press Send.<br> <input type="text" id=m cols=40 rows=1> <button id=b>Send</button> <button id="update-db">Update Database</button> <button id="get-config" onclick="send_to_ws('get-config')">Get Config</button> </body> </body> <script> var publisher_ws = new WebSocket("ws://localhost:1401", "protocol"); var padra_config_ws = new WebSocket("ws://localhost:1401", "config"); try { publisher_ws.onopen = function () { document.getElementById("m").disabled = 0; }; publisher_ws.onmessage = function got_packet(msg) { document.getElementById("r").value = document.getElementById("r").value + msg.data + "\n"; document.getElementById("r").scrollTop = document.getElementById("r").scrollHeight; }; padra_config_ws.onmessage = function got_packet(msg) { document.getElementById("r").value = document.getElementById("r").value + msg.data + "\n"; document.getElementById("r").scrollTop = document.getElementById("r").scrollHeight; }; publisher_ws.onclose = function () { document.getElementById("m").disabled = 1; }; } catch (exception) { alert("<p>Error " + exception); } function sendmsg() { publisher_ws.send(document.getElementById("m").value); document.getElementById("m").value = ""; } function updatedb_handler() { var jj = { 'type': 'update-db', 'data': { 'time': 'now' } }; console.log('type is: ', jj.type); console.log(JSON.stringify(jj)); publisher_ws.send(JSON.stringify(jj)); } function getconfig_handler(){ var jj = { 'type': 'get-config', 'data': { 'time': 'now' } }; publisher_ws.send(JSON.stringify(jj)); } function send_to_ws(name){ var jj = { 'type': name, 'data': { 'time': 'now' } }; publisher_ws.send(JSON.stringify(jj)); } document.getElementById("b").addEventListener("click", sendmsg); document.getElementById("update-db").addEventListener("click", updatedb_handler); </script> how can convert into autoit? Link to comment Share on other sites More sharing options...
Danp2 Posted May 11, 2021 Share Posted May 11, 2021 Have you looked at @FireFox's example? TheXman 1 Latest Webdriver UDF Release Webdriver Wiki FAQs Link to comment Share on other sites More sharing options...
r2du-soft Posted May 11, 2021 Author Share Posted May 11, 2021 (edited) yes i try all example but not solved The above code (autoit Code in first post) is worked but just return first line of output {"type": "update-db-start","data": { }} Edited May 11, 2021 by r2du-soft Link to comment Share on other sites More sharing options...
Danp2 Posted May 11, 2021 Share Posted May 11, 2021 @r2du-soft That was clear from your OP, so repeating it didn't change anything. Maybe someone else will have some ideas for you. Latest Webdriver UDF Release Webdriver Wiki FAQs Link to comment Share on other sites More sharing options...
JockoDundee Posted May 12, 2021 Share Posted May 12, 2021 Don't know if it matters, but I am reading a similar json page, but using: While _WinHttpQueryDataAvailable($hRequest) And @extended as conditions for the loop, and it works fine. Code hard, but don’t hard code... Link to comment Share on other sites More sharing options...
argumentum Posted May 14, 2021 Share Posted May 14, 2021 (edited) On 5/10/2021 at 3:57 PM, r2du-soft said: Local $sURL_Port = "http://localhost:1401" So, is it http or https ?. The question is because, if is http, is just clear text TCP and you could just send the http request as a header and a body. What separates a header and a body in html is "@CRLF & @CRLF", that's all. So, forget javascript and do your own TCP interaction. Plus you'd learn a lot about these "magical" functions On 5/11/2021 at 9:34 AM, r2du-soft said: var publisher_ws = new WebSocket("ws://localhost:1401", "protocol"); if is a websocket, then.... good luck ?. The handshake, etc. ... too much for me. But it could be written. Is an open standard. I hope this post clarifies that a websocket is not just a request for a stream/file and close port. ( a hint of TCP usage: https://www.autoitscript.com/forum/topic/201673-json-http-post-serverlistener/page/2/?tab=comments#comment-1447447 ) Edited May 14, 2021 by argumentum added link Follow the link to my code contribution ( and other things too ). FAQ - Please Read Before Posting. Link to comment Share on other sites More sharing options...
Danyfirex Posted May 14, 2021 Share Posted May 14, 2021 It possible using WinHttp API (I don't have time now for check deeply) but If you're have IE11 You could use this trick: expandcollapse popup#include <IE.au3> #include <String.au3> HotKeySet("{ESC}", "Terminate") HotKeySet("{F1}", "_WSSend") Global $oIE = _IECreate("about:blank", 0, 0) Global $sHTML = _wsHtml() _IEDocWriteHTML($oIE, $sHTML) _IEAction($oIE, "refresh") Global $oInput = _IEGetObjById($oIE, "myTextarea") _IEHeadInsertEventScript($oIE, $oInput, "onclick", "return false;") ObjEvent($oInput, "_Evt_") While Sleep(30) WEnd Func _WSSend() Local $aArray[] = ["Danyfirex", "r2du-soft", "AutoIt"] Local $sSomething = "Hello " & $aArray[Random(0, 2, 1)] $oIE.document.parentwindow.execScript('eval("ws.send(JSON.stringify({message:''' & $sSomething & '''}));")') EndFunc ;==>_WSSend Func Terminate() $oIE.document.parentwindow.execScript('eval("ws.send(JSON.stringify({message:''' & "Bye Bye!!!" & '''}));")') Sleep(1000) _IEQuit($oIE) ProcessClose("iexplore.exe") Exit EndFunc ;==>Terminate Func _Evt_onclick() Local $o_Input = @COM_EventObj Local $sString = $o_Input.innertext ConsoleWrite("Echo: " & $sString & @CRLF) EndFunc ;==>_Evt_onclick Func _wsHtml($wsUrl = "ws://echo.websocket.org") Local $sHTML = '<!DOCTYPE HTML>' & @CRLF & _ '<html>' & @CRLF & _ ' <head>' & @CRLF & _ ' <script type="text/javascript">' & @CRLF & _ ' var JSglobal = (1,eval)("this");' & @CRLF & _ ' var ws = new WebSocket(''' & $wsUrl & ''');' & @CRLF & _ 'ws.onopen = function(evt) {' & @CRLF & _ ' ws.send(JSON.stringify({message:''Started''}));' & @CRLF & _ '};' & @CRLF & _ 'ws.onmessage = function(msg) {' & @CRLF & _ ' var data = JSON.parse(msg.data);' & @CRLF & _ ' document.getElementById("myTextarea").value =msg.data;' & @CRLF & _ ' document.getElementById("myTextarea").click();' & @CRLF & _ '};' & @CRLF & _ ' </script>' & @CRLF & _ ' </head>' & @CRLF & _ ' <body>' & @CRLF & _ '<textarea rows="4" cols="50" id="myTextarea" style="display:none;" >' & @CRLF & _ '</textarea>' & @CRLF & _ ' </body>' & @CRLF & _ '</html>' & @CRLF Return $sHTML EndFunc ;==>_wsHtml Saludos Danysys.com AutoIt... UDFs: VirusTotal API 2.0 UDF - libZPlay UDF - Apps: Guitar Tab Tester - VirusTotal Hash Checker Examples: Text-to-Speech ISpVoice Interface - Get installed applications - Enable/Disable Network connection PrintHookProc - WINTRUST - Mute Microphone Level - Get Connected NetWorks - Create NetWork Connection ShortCut Link to comment Share on other sites More sharing options...
TheXman Posted May 14, 2021 Share Posted May 14, 2021 (edited) On 5/11/2021 at 10:37 AM, r2du-soft said: yes i try all example but not solved @r2du-soft The example referenced by @Danp2 that was posted by @FireFox is an excellent example of how to establish a websocket client to send/receive websocket messages, using the WinHTTP UDF lib. The example adds a few of the Microsoft WebSocket Protocol Component API functions & constants that are needed to do basic websocket processing, and names them as if they were WinHTTP UDF lib functions. So you saying that you tried it and it didn't solve/work, can only mean that you didn't understand it well enough to get it to work. It definitely works as long as the host running the script is Windows 8 or newer. So if you tried it and it didn't work, maybe if you post the code you tried, others might be able to steer you in the right direction. Edited May 15, 2021 by TheXman CryptoNG UDF: Cryptography API: Next Gen jq UDF: Powerful and Flexible JSON Processor | jqPlayground: An Interactive JSON Processor Xml2Json UDF: Transform XML to JSON | HttpApi UDF: HTTP Server API | Roku Remote: Example Script About Me How To Ask Good Questions On Technical And Scientific Forums (Detailed) | How to Ask Good Technical Questions (Brief) "Any fool can know. The point is to understand." -Albert Einstein "If you think you're a big fish, it's probably because you only swim in small ponds." ~TheXman Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now