Jump to content

WebSocket wait to return output line by line

Recommended Posts

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:

#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

; See what's returned
Local $sReturned
If _WinHttpQueryDataAvailable($hRequest) Then ; if there is data
        $sReturned &= _WinHttpReadData($hRequest)
    Until @error
; Close handles

; 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 by r2du-soft
Link to post
Share on other sites

Thanks Danp2

this is my java script code

<!DOCTYPE html>
<title>Websocket example</title>

    <p id="num"></p>

        <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...
        <textarea id=r readonly cols=265 rows=30></textarea><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>



    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 =
        padra_config_ws.onmessage = function got_packet(msg) {
            document.getElementById("r").value =
                document.getElementById("r").value + msg.data + "\n";
            document.getElementById("r").scrollTop =

        publisher_ws.onclose = function () {
            document.getElementById("m").disabled = 1;
    } catch (exception) {
        alert("<p>Error " + exception);

    function sendmsg() {
        document.getElementById("m").value = "";

    function updatedb_handler() {
        var jj = { 
            'type': 'update-db',
            'data': { 'time': 'now' } 
        console.log('type is: ', jj.type);

    function getconfig_handler(){
        var jj = { 
            'type': 'get-config',
            'data': { 'time': 'now' } 

    function send_to_ws(name){
        var jj = { 
            'type': name,
            'data': { 'time': 'now' } 

    document.getElementById("b").addEventListener("click", sendmsg);
    document.getElementById("update-db").addEventListener("click", updatedb_handler);



how can convert into autoit?

Link to post
Share on other sites
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 by argumentum
added link
Link to post
Share on other sites

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


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

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!!!" & '''}));")')
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




Link to post
Share on other sites
On 5/11/2021 at 10:37 AM, r2du-soft said:

yes i try all example but not solved


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 by TheXman
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...