Jump to content

Recommended Posts

Posted (edited)

AutoIt's WebSocket story usually stops at "a client that can dial out". This one does both
directions, ships no binary, and does not call WinHTTP COM, curl, PowerShell or .NET.

You get a WebSocket endpoint inside an AutoIt script, and an AutoIt script that dials a real
wss:// server - with TLS verification that actually verifies - in about fifteen lines of code.


WHAT IS IN THE PACKAGE

WebSocket.au3        the only include you write. It orders the four layers, contains no function.
wsk.au3              layer 1 - Winsock 2, non-blocking sockets, connect race, address walk
tls.au3              layer 2 - Schannel TLS records, client side and server side
wsp.au3              layer 3 - the websocket.dll protocol component: framing, close handshake
ws.au3               layer 4 - the caller API: _WS_Startup, _WS_Connect, _WS_Send, _WS_Call,
                     _WS_Pump, _WS_WaitMessage, _WS_Listen, _WS_Accept, _WS_UpgradeHead,
                     _WS_UpgradeAnswer, _WS_Close

examples/            four programs, all run before release
 

210 documented public functions, every one of them with : syntax, parameters,
return values, @error codes, and a Remarks line that says what was measured.


WHY IT IS WORTH A LOOK

- Nothing to install and nothing to trust. No DLL is shipped, no download, no third-party binary.
  The layers name only DLLs that are already in Windows (ws2_32, secur32, bcrypt and the WebSocket
  component websocket.dll). If your security review forbids shipping binaries, this passes.
- Client AND server. Host an endpoint from a script: a browser page, a phone app, a Python or Node
  service can connect TO AutoIt, not only the other way round.
- Verified against other implementations, not only against itself. The TLS layer was tested against
  Python's ssl stack and against public echo services. That is the only interesting test, because it
  is where the other side is not your code.
- TLS verification is real. An untrusted chain is refused before the upgrade, and the peer name is
  checked. You can opt out with a flag, and the flag is loud about it.
- Layered on purpose. 95 % of scripts will only ever call layer 4. If you need your own socket, your
  own TLS records or your own frame handling, layers 1 to 3 are usable on their own and are the same  code the top layer uses.

- Errors are named, not mysterious. A failure tells you the step, the Winsock or HRESULT code, and a
  text. A refused connection and a refused handshake are two different answers.
- 32-bit and 64-bit, same behaviour, both tested. No admin rights.


REQUIREMENTS

AutoIt 3.3.16.1 and Windows 8 or later (that is the floor stated by the library, the WebSocket
component does not exist before it; everything here was measured on Windows 10 19045). Nothing else.


INSTALL

Extract the archive next to your script. Five files make the UDF run - the umbrella and its four
layers - and none of them is generated at run time. Then:

  #include "WebSocket\WebSocket.au3"


THE WHOLE CLIENT, IN ONE PROGRAM

#include "..\WebSocket.au3"

If Not _WS_Startup() Then Exit 1

Local $h = _WS_Connect("ws://127.0.0.1:8181/chat")
If $h < 0 Then
    ConsoleWrite("step " & @error & "/" & @extended & " :: " & _WS_ErrorText(-1) & @CRLF)
    ConsoleWrite("addresses: " & _WS_LastWalk() & @CRLF)
    _WS_Cleanup()
    Exit 1
EndIf

Local $b = _WS_Call($h, "hello", 8000)
If @error Then
    ConsoleWrite("round trip failed: " & _WS_ErrorText($h) & @CRLF)
Else
    ConsoleWrite("answer: " & BinaryToString($b, 8) & @CRLF)
EndIf

_WS_Close($h, 1000, "done", 2000)
_WS_Cleanup()

_WS_Connect takes a URL and does the address race, the TLS handshake if the scheme is wss, and the
HTTP upgrade. _WS_Call sends one message and waits for the answer. If it fails, @error is the step
and @extended the system code, and _WS_ErrorText() plus _WS_LastWalk() tell you what happened
without a debugger.


THE WHOLE SERVER, IN ONE PROGRAM

#include "..\WebSocket.au3"

If Not _WS_Startup() Then Exit 1
Local $hl = _WS_Listen(8181)                       ; 127.0.0.1, plain ws://
If $hl < 0 Then
    ConsoleWrite("cannot listen: " & _WS_ErrorText(-1) & @CRLF)
    _WS_Cleanup()
    Exit 1
EndIf
ConsoleWrite("listening on " & _WS_ListenPort($hl) & @CRLF)

While 1
    Local $h = _WS_Accept($hl)                     ; -1 = nobody is dialing now
    If $h < 0 Then
        Sleep(10)                                  ; _WS_Accept never waits, so the loop must
        ContinueLoop
    EndIf
    If _WS_UpgradeHead($h, 4000) < 0 Then          ; the request head first
        _WS_CloseRefused($h, "400 Bad Request", 2000)
        ContinueLoop
    EndIf
    ConsoleWrite("path=" & _WS_Path($h) & " origin=" & _WS_RequestHeader($h, "Origin") & @CRLF)
    If _WS_UpgradeAnswer($h, "", "", 4000) < 0 Then    ; accept, no subprotocol
        _WS_CloseHandle($h)
        ContinueLoop
    EndIf
    Local $b = _WS_WaitMessage($h, 8000)
    If @error = 0 Then _WS_Send($h, BinaryToString($b, 8))
    _WS_Flush($h, 3000)
    _WS_Close($h, 1000, "", 2000)
WEnd

Two calls instead of one, on purpose: _WS_UpgradeHead reads what the peer actually asked - path,
Origin, offered subprotocols - and only then do you decide to accept, pick a subprotocol, or refuse
with a real HTTP status. A server that cannot see the request head before saying yes cannot check
an Origin, and that is a security hole, not a convenience.

examples/example_server.au3 and examples/example_client.au3 are the same pair with TLS, Origin
checking, subprotocol selection and several messages in flight. Both printed programs above ship in
the archive as examples/hello_server.au3 and examples/hello_client.au3.


DOCUMENTATION

The attached WebSocket_Quick_Start.pdf is 11 pages: install, the client, the server, the pump,
wss and certificates, error reading, a chapter on what a browser is allowed to do with this, and a
chapter of copy-paste recipes. Read chapter 02 and 05 and you can write anything in the UDF.


WHAT IT IS FOR

- A script that needs a live feed: prices, telemetry, a chat room, a job queue, a device console.
- Replacing a polling HTTP API with a pushed one, on a machine where you cannot install anything.
- Letting a web page, a phone or another language talk TO an AutoIt script that keeps running.
- A bridge: AutoIt still owns the desktop, the GUI and the legacy app, and a browser UI drives it.


KNOWN LIMITATIONS

Everything below is measured. Each item says what actually happens, so you are not left debugging
something that was merely undocumented.

1. Ping cannot be initiated. The Windows WebSocket component answers WebSocketSend with a PING_PONG
   buffer by E_INVALIDARG (0x80070057) and schedules no network action at all. _Wsp_Ping() exists so
   that you get a named failure instead of a false success. Inbound pings are fine: the component
   answers them with a pong on its own, proved against a third-party client that received our pong
   although we never wrote one. Do keepalive at application level - one data frame answered by the
   peer is a round trip you can actually time, and that is what _WS_Call() is for.

2. Close codes 1005 and 1006 are never put on the wire, and out-of-range values are not refused
   either: both cases are replaced by 1000 before the answer leaves. That is RFC behaviour for those
   two codes, but it means the code alone cannot tell you "no status frame arrived" from "closed
   abnormally". The field that does tell you those apart is fromPeer= in _WS_CloseInfo($h): a real
   close frame sets it to 1 and carries its code and reason (measured in the suite: code=1000,
   code=1001 reason=[moving away]), while a peer that drops the socket leaves code=0 fromPeer=0.
   A close is also never queued behind data: it surfaces through the type returned by the pump call
   that saw it.

3. TLS 1.3 was never observed, in either direction, on this machine. Measured on 2026-11-17 with
   certificate verification ON ($fIgnoreRoot = False, so Windows validated the chain and the host name
   each time): ws.postman-echo.com, echo.websocket.org and echo-websocket.fly.dev all settled on
   TLS 1.2 (protocol 0x00000800, ECDHE-RSA-AES256-GCM-SHA384 or AES128-GCM), at both 32-bit and 64-bit,
   open 596 to 2 885 ms, echo answered every time. The version reporter in tls.au3 has a TLS 1.3
   branch and it has never fired - not against those public servers, and not against a local peer that
   offers 1.3. That is the floor of the operating system, not of the UDF: Schannel added TLS 1.3 in
   Windows 11 and Windows Server 2022, and this suite ran on Windows 10 19045. If you run it on
   Windows 11 and get a TLS 1.3 session, tell me - the record format differs and I have not been able
   to test it.

4. You drive the pump. No timer, no Adlib, no thread inside the UDF: messages move when you call
   _WS_Pump($h) or _WS_WaitMessage($h, $iTimeoutMs). In a GUI script that normally means one pump call
   per GUIGetMsg() turn, and a bare GUIGetMsg loop turns about 60 times a second, so that is the
   delivery ceiling. Two consequences: never call a sending function from inside _Wsp_PumpOnce (the
   send re-enters the pump and wipes the shared structures mid-read - that one segfaulted during
   development), and a peer that stops answering costs you at most the budget you passed.

5. Fixed ceilings per process, all compile-time constants: 8 concurrent connections ($g_iWspSlots) and
   8 listeners ($g_iWsListeners). Both show up in the logs, as cap=8 and on every listener line. The
   receive cap is 4 MiB per message by default ($iMaxMsg, the same figure IIS documents for
   receiveBufferLimit) and is settable per listen or per connect; the TLS record buffer is 65536 +
   32768 bytes per slot. What is measured about overflow: a delivery queue that fills is counted in
   dropped= and surfaces as the pump's @error 3, with the dropped count in @extended - bounded memory
   plus a loud failure, never silent buffering.

6. No extensions. The UDF never offers and never selects one: permessage-deflate appears nowhere in the
   sources. Every session in the suite produced a plain 101 with no extension selected. A peer that
   explicitly offered an extension has not been exercised, so do not read more into this line than
   that.

7. No reconnection, no HTTP body, no routing. It is a transport layer. After a closed connection you
   call _WS_Connect again yourself. The server answers the upgrade handshake and then speaks frames
   only: the 101 is written by the Windows component, the 405 to a non-GET request is written by this
   UDF (_WS_Upgrade checks _WS_Method), and neither answer carries a body. Both refusals are measured:
   method refused:

c4s0 ANSWER refused step 2/S_OK :: Origin refused [http://evil.example] allow=[http://good.example]
SUMMARY c4s0 messages=0 bytes=0 errors=0 why=answer step 2

8. Trust is Windows' own.
Verification goes through the Schannel chain policy, so a self-signed certificate is refused
before the upgrade unless you pass the ignore-root flag. Measured both ways: with
$fIgnoreRoot = False, a connect to a name whose chain ends in an untrusted root fails at the
policy step with 0x800B0109, and the verdict text is returned by _WS_ErrorText($h); with the
flag set, the same session opens and the log says approved. The flag does not weaken the host
name check. The certificate used by the TLS examples is a test certificate and is deliberately
not trusted. Use a real certificate; do not ship the flag.

9. Scope of testing.
AutoIt 3.3.16.1, both interpreters, one Windows 10 machine (19045), against our own server,
against Python's ssl and websocket stacks (OpenSSL 3.0.15, websockets 17.2), and against the
three public echo servers named in item 3. The guard gate replays 19 suites at both bitnesses -
38 runs - and the last recorded run finished with 38 zero return codes, with the failure
counters read inside the logs and not just the exit codes. Nothing was run on Windows Server
SKUs or behind a proxy, and no TLS 1.3 session was ever observed.

 

VERSION AND LICENCE

1.0.0, MIT licence (see LICENSE in the archive).
If you hit something, post the bitness, the step and the two codes: the return value, @error
(step) and @extended (system code), plus the output of _WS_ErrorText($h) and, for a failed
connect, _WS_LastWalk(). Those four lines are enough for me to reproduce almost anything.

 

WebSocket.zip

 

WebSocket_Quick_Start.pdf

 

Edited by Numeric1
From 0 and 1 to the stars, it all starts with binary, Numeric1
 
Posted

Added your UDF to the Wiki 🙂 .

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Posted (edited)

Live example: a GUI reading a public wss feed, and the one rule that made it stop stuttering

BINANCE.PNG.2532d50e80ba1fef68fbf220ab878e26.PNG

Attached is a complete program: a small dark GUI that watches the public BTC/USDT trade feed
(32 and 64 bit, AutoIt 3.3.16.1, no third-party DLL). It is deliberately a reader example -
a server cannot show this, because the problem is how a paint loop and a socket loop share one thread.

The first version looked correct and stuttered badly. Measured over 10 s windows on the live feed:

UNGATED   turns=155  pumps=146  time inside _WS_Pump=78 pct  messages=32   0.22 msg per pump
GATED     turns=554  pumps= 14  time inside _WS_Pump= 2 pct  messages=53   3.8  msg per pump

The reason: one turn of the pump lets the socket 50 ms to speak, and the caller's budget is tested
at the end of a turn. So _WS_Pump($h, 12) on an idle connection blocks the
GUI thread for about 50 ms out of every 60, Windows queues its paints, and they come out in bursts.
That is the strobe. The fix is to pump only when there is something to pump:

Func _HasWork()
    Local $iTls = $g_aWs_Tls[$hWS]
    If $iTls >= 0 Then
        ; wss:// owns its socket in layer 2; the layer 3 copy is 0
        If _Tls_Available($iTls) > 0 Then Return True
        Return (_Wsk_Poll($g_aTls_Sock[$iTls], $Wsk_POLLRDNORM, 0) <> 0)
    EndIf
    Return (_Wsk_Poll($g_aWsp_Socket[$hWS], $Wsk_POLLRDNORM, 0) <> 0)
EndFunc

Two things that cost me an hour each, both worth writing down:

  • In wss:// the socket belongs to layer 2.$g_aWsp_Socket[$h] is 0, so a
    readiness poll on it answers "nothing readable" forever and the stream never starts. Measured:
    wspSocket=0, tlsSocket=0x00000454.
  • The drain loop reads the layer 3 numbers._WS_WaitMessage($h, 0)
    passes them through: 1 = nothing waiting (the normal way out of the loop, not an error), 3 = the peer
    closed and then the close code is in @extended while the returned value is the peer's reason
    text, 5 = delivery queue full with the loss count in @extended. Treating every non-zero as fatal
    kills the connection the first time the feed pauses.

The rest is ordinary GUI hygiene, and it matters less than the pump: no
$WS_EX_COMPOSITED (it repaints the whole window on every control change), an
opaque background on each label, one GUICtrlCreateListViewItem per row with the
"|" separator instead of four control calls, and rendering separated from reading - messages fill
variables, and one paint per 200 ms draws them. The feed itself pushes 3 to 44 messages per second
depending on the market, so at any refresh rate the price still moves: that is a quotation, not a bug.

Run it with --selftest 10 and it checks the transport without opening a window:

SELFTEST turns=554 pumpedTurns=14 pctTurnsPumped=2 messages=53 perSec=5
         price=64299.99000000 qty=0.01312000 side=Sell dropped=0 elapsedMs=10014
RESULT ok=1 fail=0

The program needs the UDF folder next to it, and the URL is the public Binance trade stream. If your
proxy blocks it, the self-test prints a skip line instead of a failure - that is the network, not the code.

#NoTrayIcon
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>
#include <StaticConstants.au3>
#include <GuiListView.au3>
#include <ColorConstants.au3>

#include "..\WebSocket.au3"          ; adjust the path if you move this file

Opt("GUIOnEventMode", 0)
Opt("MustDeclareVars", 1)

; ===================== Globals =====================
Global $hWS = -1
Global $fConnected = False
Global $sURL = "wss://stream.binance.com:9443/ws/btcusdt@trade"

; Controls
Global $hGUI, $lblStatus, $lblPrice, $lblInfo
Global $btnConnect, $btnDisconnect, $lvLog, $editRaw

; Newest from the stream, and what is already on screen
Global $sLastPrice = "", $sLastQty = "", $sLastSide = "", $sLastRaw = ""
Global $fRowPending = False
Global $iDropped = 0
Global $iRemembered = 0
Global $iPumpCalls = 0
Global $hTimerRender = 0
Global Const $RENDER_MS = 200                  ; 5 paints/s: the feed pushes 31 to 44
Global Const $PUMP_BUDGET = 12                 ; ms; see _HasWork(), it is no longer called idle
Global Const $MAX_ROWS = 35

; --selftest <seconds>: check the transport without creating a window
Global $iSelfTest = 0
If $CmdLine[0] >= 2 And $CmdLine[1] = "--selftest" Then $iSelfTest = Int($CmdLine[2])
If $iSelfTest > 0 Then Exit _SelfTest()

; ===================== GUI =====================
; No $WS_EX_COMPOSITED: it repaints the whole window on every control change, which is exactly
; what turns one update into a visible strobe.
$hGUI = GUICreate("WebSocket Client - Live BTC/USDT", 740, 540)
GUISetBkColor(0x1E1E1E)

GUICtrlCreateLabel("WebSocket client - live observation", 20, 12, 500, 28)
GUICtrlSetFont(-1, 14, 600, 0, "Segoe UI")
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetBkColor(-1, 0x1E1E1E)

GUICtrlCreateLabel("Status:", 20, 52, 55, 20)
GUICtrlSetColor(-1, 0xAAAAAA)
GUICtrlSetBkColor(-1, 0x1E1E1E)
$lblStatus = GUICtrlCreateLabel("Disconnected", 80, 52, 300, 20)
GUICtrlSetFont(-1, 10, 600)
GUICtrlSetColor(-1, 0xFF5555)
GUICtrlSetBkColor(-1, 0x1E1E1E)

GUICtrlCreateLabel("BTC/USDT price:", 20, 85, 120, 20)
GUICtrlSetColor(-1, 0xAAAAAA)
GUICtrlSetBkColor(-1, 0x1E1E1E)
$lblPrice = GUICtrlCreateLabel("---", 145, 80, 280, 32)
GUICtrlSetFont(-1, 18, 700)
GUICtrlSetColor(-1, 0x00FF88)
GUICtrlSetBkColor(-1, 0x1E1E1E)

$lblInfo = GUICtrlCreateLabel("Waiting for a connection...", 20, 120, 700, 20)
GUICtrlSetColor(-1, 0x888888)
GUICtrlSetBkColor(-1, 0x1E1E1E)

$btnConnect = GUICtrlCreateButton("Connect", 530, 48, 180, 34)
GUICtrlSetBkColor(-1, 0x2D7D46)
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetFont(-1, 10, 600)

$btnDisconnect = GUICtrlCreateButton("Disconnect", 530, 90, 180, 34)
GUICtrlSetBkColor(-1, 0x8B2E2E)
GUICtrlSetColor(-1, 0xFFFFFF)
GUICtrlSetFont(-1, 10, 600)
GUICtrlSetState(-1, $GUI_DISABLE)

GUICtrlCreateLabel("Recent trades:", 20, 155, 200, 20)
GUICtrlSetColor(-1, 0xAAAAAA)
GUICtrlSetBkColor(-1, 0x1E1E1E)

$lvLog = GUICtrlCreateListView("Time|Price|Quantity|Side", 20, 180, 700, 230, -1, -1)
_GUICtrlListView_SetColumnWidth($lvLog, 0, 130)
_GUICtrlListView_SetColumnWidth($lvLog, 1, 170)
_GUICtrlListView_SetColumnWidth($lvLog, 2, 170)
_GUICtrlListView_SetColumnWidth($lvLog, 3, 110)
GUICtrlSetBkColor($lvLog, 0x252526)
GUICtrlSetColor($lvLog, 0xDDDDDD)

GUICtrlCreateLabel("Last raw message:", 20, 425, 200, 18)
GUICtrlSetColor(-1, 0xAAAAAA)
GUICtrlSetBkColor(-1, 0x1E1E1E)
$editRaw = GUICtrlCreateEdit("", 20, 448, 700, 70, BitOR($ES_READONLY, $ES_AUTOVSCROLL, $WS_VSCROLL))
GUICtrlSetBkColor(-1, 0x252526)
GUICtrlSetColor(-1, 0xAAAAAA)
GUICtrlSetFont(-1, 9, 400, 0, "Consolas")

GUISetState(@SW_SHOW, $hGUI)

; ===================== Main loop =====================
While 1
    Local $nMsg = GUIGetMsg()

    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            _CloseConnection()
            Exit
        Case $btnConnect
            _Connect()
        Case $btnDisconnect
            _CloseConnection()
    EndSwitch

    If $fConnected And $hWS >= 0 Then
        _ReadOnce()
        _Render()
    EndIf

    Sleep(10)
WEnd

; ===================== Transport =====================

; The pump is expensive: every turn of it lets the socket 50 ms to speak, so calling _WS_Pump on
; an idle connection blocks the GUI thread about 50 ms out of 60 (measured: 75 to 87 percent of the
; wall clock was spent inside the pump). Pump only when there is real material: a byte on the wire,
; or bytes the TLS layer has already decrypted.
Func _HasWork()
    Local $iTls = $g_aWs_Tls[$hWS]
    If $iTls >= 0 Then
        ; wss:// owns its socket in layer 2, and the layer 3 copy is 0 (measured: wspSocket=0,
        ; tlsSocket=0x00000454). Polling the wrong descriptor answers "nothing" forever and the
        ; stream never moves.
        If _Tls_Available($iTls) > 0 Then Return True
        Return (_Wsk_Poll($g_aTls_Sock[$iTls], $Wsk_POLLRDNORM, 0) <> 0)
    EndIf
    Return (_Wsk_Poll($g_aWsp_Socket[$hWS], $Wsk_POLLRDNORM, 0) <> 0)
EndFunc   ;==>_HasWork

; One read turn: pump, then drain the delivery queue. Messages touch NO control here; they fill
; variables, and _Render() alone draws, at its own rate.
Func _ReadOnce()
    If $hWS < 0 Then Return
    If Not _HasWork() Then Return
    $iPumpCalls += 1

    _WS_Pump($hWS, $PUMP_BUDGET)
    Local $eP = @error, $xP = @extended
    Switch $eP
        Case 0
            ; normal
        Case 1
            _SetStatus("TCP closed by the peer (or the handle is gone)", 0xFF5555)
            _CloseConnection()
            Return
        Case 2
            _SetStatus("Pump error: " & _WS_ErrorText($hWS), 0xFF5555)
            _CloseConnection()
            Return
        Case 3
            ; Delivery queue full: messages are LOST, and that is said, never invented.
            $iDropped += $xP
            _SetStatus("Queue full: " & $iDropped & " messages dropped", 0xFFAA00)
    EndSwitch

    While 1
        Local $b = _WS_WaitMessage($hWS, 0)
        Local $e = @error, $x = @extended
        Switch $e
            Case 0
                ; Layer 3 already brings the type back into the signed space, so compare the
                ; constants directly, the way the shipped example does.
                If $x = $Wsp_UTF8_MESSAGE Or $x = $Wsp_BINARY_MESSAGE Then _Remember(BinaryToString($b, 8))
            Case 1
                ExitLoop                  ; nothing waiting: the normal way out of the drain
            Case 3
                ; @extended is the close code, the returned value is the peer's reason
                _SetStatus("Closed by the server (code " & $x & ") " & BinaryToString($b, 8), 0xFF5555)
                _CloseConnection()
                ExitLoop
            Case 4
                _SetStatus("Transport died in the middle of a message", 0xFF5555)
                _CloseConnection()
                ExitLoop
            Case Else
                ; 2 = pump error, 5 = delivery queue full: recoverable, the connection stays up
                If $e = 5 Then $iDropped += $x
                ExitLoop
        EndSwitch
    WEnd
EndFunc   ;==>_ReadOnce

; ===================== Rendering =====================
Func _Remember($sJson)
    Local $sPrice = _JsonGet($sJson, "p")
    If $sPrice = "" Then Return
    $sLastPrice = $sPrice
    $sLastQty = _JsonGet($sJson, "q")
    $sLastSide = (_JsonGet($sJson, "m") = "true") ? "Sell" : "Buy"
    $sLastRaw = $sJson
    $fRowPending = True
    $iRemembered += 1
EndFunc   ;==>_Remember

; One paint per $RENDER_MS window, and only when something actually changed. The row is built in
; ONE call (the "|" fills the columns) instead of four control messages.
Func _Render()
    If Not $fRowPending Then Return
    If TimerDiff($hTimerRender) < $RENDER_MS Then Return
    $hTimerRender = TimerInit()
    $fRowPending = False

    GUICtrlSetData($lblPrice, $sLastPrice & " USDT")
    GUICtrlSetData($editRaw, $sLastRaw)

    GUICtrlCreateListViewItem(@HOUR & ":" & @MIN & ":" & @SEC & "|" & $sLastPrice & "|" & $sLastQty & "|" & $sLastSide, $lvLog)
    If _GUICtrlListView_GetItemCount($lvLog) > $MAX_ROWS Then _GUICtrlListView_DeleteItem($lvLog, 0)
    _GUICtrlListView_EnsureVisible($lvLog, _GUICtrlListView_GetItemCount($lvLog) - 1)
EndFunc   ;==>_Render

Func _SetStatus($sText, $iColor)
    If $iSelfTest > 0 Then
        ConsoleWrite("STATUS " & $sText & @CRLF)
        Return
    EndIf
    GUICtrlSetData($lblStatus, $sText)
    GUICtrlSetColor($lblStatus, $iColor)
EndFunc   ;==>_SetStatus

; ===================== Connection =====================
Func _Connect()
    If $fConnected Then Return

    _SetStatus("Connecting...", 0xFFAA00)
    GUICtrlSetState($btnConnect, $GUI_DISABLE)

    If Not _WS_Startup() Then
        _SetStatus("_WS_Startup failed", 0xFF5555)
        GUICtrlSetState($btnConnect, $GUI_ENABLE)
        Return
    EndIf

    $hWS = _WS_Connect($sURL, 12000)
    If $hWS < 0 Then
        _SetStatus("Failed: " & _WS_ErrorText(-1), 0xFF5555)
        _WS_Cleanup()
        GUICtrlSetState($btnConnect, $GUI_ENABLE)
        Return
    EndIf

    $fConnected = True
    $iDropped = 0
    $hTimerRender = TimerInit()          ; a real base: TimerDiff(0) returns the machine uptime
    _SetStatus("Connected - live BTC/USDT", 0x00FF88)
    GUICtrlSetState($btnDisconnect, $GUI_ENABLE)
    GUICtrlSetData($lblInfo, "Binance feed - " & $sURL)
EndFunc   ;==>_Connect

Func _CloseConnection()
    If $hWS >= 0 Then
        _WS_Close($hWS, 1000, "Client closed", 1500)
        $hWS = -1
    EndIf
    _WS_Cleanup()
    $fConnected = False
    If $iSelfTest > 0 Then Return

    _SetStatus("Disconnected", 0xFF5555)
    GUICtrlSetData($lblPrice, "---")
    GUICtrlSetData($lblInfo, "Waiting for a connection...")
    GUICtrlSetState($btnConnect, $GUI_ENABLE)
    GUICtrlSetState($btnDisconnect, $GUI_DISABLE)
EndFunc   ;==>_CloseConnection

Func _JsonGet($sJson, $sKey)
    Local $a = StringRegExp($sJson, '"' & $sKey & '"\s*:\s*"?([^",}\]]+)"?', 1)
    If @error Then Return ""
    Return $a[0]
EndFunc   ;==>_JsonGet

; ===================== Self-test (no window) =====================
Func _SelfTest()
    If Not _WS_Startup() Then
        ConsoleWrite("RESULT fail=startup" & @CRLF)
        Return 1
    EndIf
    $hWS = _WS_Connect($sURL, 15000)
    If $hWS < 0 Then
        Local $x = @extended
        ConsoleWrite("connect err=" & @error & " ext=" & $x & " text=" & _WS_ErrorText(-1) & @CRLF)
        _WS_Cleanup()
        If $x = 11001 Or $x = 10060 Or $x = 10061 Or $x = 10054 Then
            ConsoleWrite("RESULT skip=network" & @CRLF)
            Return 0
        EndIf
        Return 1
    EndIf

    Local $t0 = TimerInit(), $iTurns = 0
    While TimerDiff($t0) < $iSelfTest * 1000 And $hWS >= 0
        $iTurns += 1
        _ReadOnce()
        Sleep(10)
    WEnd
    Local $fEl = TimerDiff($t0)
    ConsoleWrite("SELFTEST turns=" & $iTurns & " pumpedTurns=" & $iPumpCalls & _
            " pctTurnsPumped=" & Int($iPumpCalls * 100 / ($iTurns > 0 ? $iTurns : 1)) & _
            " messages=" & $iRemembered & " perSec=" & Int($iRemembered * 1000 / $fEl) & _
            " price=" & $sLastPrice & " qty=" & $sLastQty & " side=" & $sLastSide & _
            " dropped=" & $iDropped & " elapsedMs=" & Int($fEl) & @CRLF)
    If $hWS >= 0 Then _WS_Close($hWS, 1000, "selftest", 2000)
    $hWS = -1
    _WS_Cleanup()
    If $sLastPrice = "" Then
        ConsoleWrite("RESULT fail=no_price" & @CRLF)
        Return 1
    EndIf
    ConsoleWrite("RESULT ok=1 fail=0" & @CRLF)
    Return 0
EndFunc   ;==>_SelfTest

 

Edited by Numeric1
From 0 and 1 to the stars, it all starts with binary, Numeric1
 
Posted
36 minutes ago, argumentum said:

...The motivation behind the motivation :P :lol:

The motivation behind the motivation is a feed that pushes 3 to 44 messages per second that nobody
asked for. An echo server only speaks when spoken to, so it never tests the part that actually
breaks: a pump shared with a paint loop. Binance is the excuse, the frame rate is the point. :P😁

From 0 and 1 to the stars, it all starts with binary, Numeric1
 

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
×
×
  • Create New...