Skip to content

WebSocket Fails with HTTPS Enabled: OSError -30464 in adafruit_httpserver #10093

Open
adafruit/Adafruit_CircuitPython_HTTPServer
#114

Description

@berkut0

CircuitPython version and board name

Adafruit CircuitPython 9.2.4 on 2025-01-29; Wemos Lolin C3 Mini with ESP32-C3FH4

Code/REPL

import wifi
import socketpool
import asyncio
from adafruit_httpserver import Server, Request, Response, Websocket, GET

pool = socketpool.SocketPool(wifi.radio)

server = Server(
    pool,
#     root_path="/static",
    https=True,
    certfile="cert.pem",
    keyfile="key.pem",
    debug=True)

websocket: Websocket = None

@server.route("/ws", GET)
def connect_client(request: Request):
    global websocket  # pylint: disable=global-statement
    if websocket is not None:
        websocket.close()  # Close any existing connection
    websocket = Websocket(request)
    return websocket

async def handle_http_requests():
    while True:
        server.poll()
        await asyncio.sleep_ms(0)

async def handle_websocket_requests():
    while True:
        if websocket is not None:
            if (data := websocket.receive(fail_silently=True)) is not None:
                print(data)
        await asyncio.sleep_ms(0)

async def send_websocket_messages():
    while True:
        if websocket is not None:
            websocket.send_message("aaaa", fail_silently=True)
        await asyncio.sleep_ms(1000)

server.start(str(wifi.radio.ipv4_address))

async def main():
    await asyncio.gather(
        asyncio.create_task(handle_websocket_requests()),
        asyncio.create_task(send_websocket_messages()),
        asyncio.create_task(handle_http_requests())
        )

asyncio.run(main())

Behavior

When HTTPS is enabled (by providing certificate and key files), static content is served correctly; however, WebSocket connections fail. Testing with a C# Watson WebSocket client produces the error:

Traceback (most recent call last):
  File "adafruit_httpserver/server.py", line 476, in poll
OSError: -30464
Traceback (most recent call last):
  File "code.py", line 101, in <module>
  File "asyncio/core.py", line 317, in run
  File "asyncio/core.py", line 276, in run_until_complete
  File "asyncio/core.py", line 261, in run_until_complete
  File "code.py", line 98, in main
  File "asyncio/funcs.py", line 162, in gather
  File "asyncio/core.py", line 261, in run_until_complete
  File "code.py", line 39, in handle_http_requests
  File "adafruit_httpserver/server.py", line 528, in poll
  File "adafruit_httpserver/server.py", line 476, in poll
OSError: -30464

This issue disappears when HTTPS is disabled (i.e., when the certificate-related parameters are commented out).

   server = Server(
       pool,
       # https=True,
       # certfile="cert.pem",
       # keyfile="key.pem",
       debug=True)

Expected Behavior:
WebSocket connections should be established successfully regardless of whether HTTPS is enabled, while still serving static content securely.

Actual Behavior:
With HTTPS enabled, WebSocket connections fail with the error OSError: -30464 during the polling process.

Additional Context:

  • The issue appears to be isolated to WebSocket functionality when using HTTPS.
  • The rest of the HTTP functionality (e.g., serving static content) is unaffected.
  • This behavior was reproduced on a CircuitPython environment using the adafruit_httpserver library.

Activity

  1. added this to the 9.2.x milestone on Feb 24, 2025
  2. modified the milestones: 9.2.x, 9.x.x on Mar 17, 2025
  3. modified the milestones: 9.x.x, 10.x.x on Mar 17, 2025
  4. modified the milestones: 10.x.x, 10.3.0 on May 19, 2026
  5. dhalbert commented on Jun 17, 2026

    @dhalbert
    Collaborator

    This is an old bug. I'd like to re-test it with recent builds. Do you have a simple client, or shell commands, that could test it? Thanks.

  6. modified the milestones: 10.3.0, 10.x.x on Jun 28, 2026
  7. berkut0 commented on Jun 30, 2026

    @berkut0
    Author

    Re-tested on Adafruit QT Py ESP32-C3, CircuitPython 10.2.1 (2026-05-13).

    Observation

    On the original report (ESP32-C3, HTTPS enabled), the server appeared to start and serve static content, but a WebSocket client caused OSError: -30464 inside server.poll(), which took down the whole asyncio loop.

    On my board with CP 10.2.1, enabling HTTPS no longer gets that far: server.start() raises MemoryError in _create_server_socket before the server is running. So on this hardware the failure happens early, as a clear out-of-memory error, instead of a later TLS/WebSocket crash that stops the entire program. That seems like an improvement in how the failure is surfaced, even though HTTPS + WebSocket is still not usable on ESP32-C3.

    I could not reproduce -30464 here because HTTPS does not start on this board. That error may still apply on boards with enough RAM to bring up the TLS server (e.g. ESP32-S3).

    What works: HTTP + ws:// (no TLS).

    Server (code.py on device):

    import gc
    import time
    import wifi
    import socketpool
    import asyncio
    from adafruit_httpserver import Server, Request, Websocket, GET
    
    while not wifi.radio.connected:
        time.sleep(0.1)
    
    pool = socketpool.SocketPool(wifi.radio)
    server = Server(pool, debug=False)
    
    websocket = None
    HOST = str(wifi.radio.ipv4_address)
    PORT = 5000
    
    @server.route("/ws", GET)
    def connect_client(request):
        global websocket
        if websocket is not None:
            websocket.close()
        websocket = Websocket(request)
        return websocket
    
    async def handle_http_requests():
        while True:
            server.poll()
            await asyncio.sleep_ms(0)
    
    async def handle_websocket_requests():
        while True:
            if websocket is not None:
                if (data := websocket.receive(fail_silently=True)) is not None:
                    print(data)
            await asyncio.sleep_ms(0)
    
    async def send_websocket_messages():
        while True:
            if websocket is not None:
                websocket.send_message("aaaa", fail_silently=True)
            await asyncio.sleep_ms(1000)
    
    gc.collect()
    server.start(HOST, PORT)
    
    async def main():
        await asyncio.gather(
            asyncio.create_task(handle_http_requests()),
            asyncio.create_task(handle_websocket_requests()),
            asyncio.create_task(send_websocket_messages()),
        )
    
    asyncio.run(main())

    Client (PC — pip install websockets):

    import asyncio
    import ssl
    import sys
    import websockets
    
    async def test(uri):
        ssl_ctx = None
        if uri.startswith("wss://"):
            ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
            ssl_ctx.check_hostname = False
            ssl_ctx.verify_mode = ssl.CERT_NONE
    
        async with websockets.connect(uri, ssl=ssl_ctx, open_timeout=10) as ws:
            print("recv:", await asyncio.wait_for(ws.recv(), timeout=10))
            await ws.send("ping")
            print("sent: ping")
    
    asyncio.run(test(sys.argv[1]))

    Run:

    python test_ws_client.py ws://<device-ip>:5000/ws
    

    Expected: recv: aaaa, then sent: ping.

  8. berkut0 commented on Jun 30, 2026

    @berkut0
    Author

    @dhalbert — follow-up with a minimal HTTPS / WSS repro setup for boards that have enough RAM (e.g. ESP32-S3). On ESP32-C3, server.start() still raises MemoryError before TLS comes up.

    Board

    ESP32-S3 (or similar). ESP32-C3 cannot start the HTTPS server.

    Device files

    CIRCUITPY/
    ├── code.py          # from code_https.py below
    ├── settings.toml    # CIRCUITPY_WIFI_SSID / CIRCUITPY_WIFI_PASSWORD
    ├── cert.pem
    ├── key.pem
    └── lib/adafruit_httpserver/
    

    Generate certs (host PC):

    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem -subj "/CN=circuitpython.local"
    

    Copy cert.pem and key.pem to the device root.

    Server (code.py)

    Same as original issue report, plus a / route for a simple HTTPS GET check. Listens on port 5000 (library default for server.start(host) — not 443).

    import gc
    import time
    import wifi
    import socketpool
    import asyncio
    from adafruit_httpserver import Server, Request, Response, Websocket, GET
    
    while not wifi.radio.connected:
        time.sleep(0.1)
    
    pool = socketpool.SocketPool(wifi.radio)
    
    server = Server(
        pool,
        https=True,
        certfile="cert.pem",
        keyfile="key.pem",
        debug=True,
    )
    
    websocket = None
    HOST = str(wifi.radio.ipv4_address)
    PORT = 5000
    
    @server.route("/")
    def index(request):
        return Response(request, "HTTPS OK")
    
    @server.route("/ws", GET)
    def connect_client(request):
        global websocket
        if websocket is not None:
            websocket.close()
        websocket = Websocket(request)
        return websocket
    
    async def handle_http_requests():
        while True:
            server.poll()
            await asyncio.sleep_ms(0)
    
    async def handle_websocket_requests():
        while True:
            if websocket is not None:
                if (data := websocket.receive(fail_silently=True)) is not None:
                    print(data)
            await asyncio.sleep_ms(0)
    
    async def send_websocket_messages():
        while True:
            if websocket is not None:
                websocket.send_message("aaaa", fail_silently=True)
            await asyncio.sleep_ms(1000)
    
    gc.collect()
    server.start(HOST, PORT)
    print("HTTPS: https://%s:%d/" % (HOST, PORT))
    print("WSS:   wss://%s:%d/ws" % (HOST, PORT))
    
    async def main():
        await asyncio.gather(
            asyncio.create_task(handle_http_requests()),
            asyncio.create_task(handle_websocket_requests()),
            asyncio.create_task(send_websocket_messages()),
        )
    
    asyncio.run(main())

    PC test script

    pip install websockets, then save as test_https_wss.py:

    import asyncio
    import ssl
    import sys
    import urllib.request
    import websockets
    
    def ssl_context():
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        return ctx
    
    def test_https(host, port):
        url = "https://%s:%d/" % (host, port)
        print("HTTPS GET", url)
        with urllib.request.urlopen(url, context=ssl_context(), timeout=10) as resp:
            print("  status:", resp.status)
            print("  body:", resp.read().decode())
    
    async def test_wss(host, port):
        uri = "wss://%s:%d/ws" % (host, port)
        print("WSS connect", uri)
        async with websockets.connect(uri, ssl=ssl_context(), open_timeout=10) as ws:
            print("  recv:", await asyncio.wait_for(ws.recv(), timeout=10))
            await ws.send("ping")
            print("  sent: ping")
    
    async def main(host, port):
        test_https(host, port)
        await test_wss(host, port)
        print("OK")
    
    if __name__ == "__main__":
        if len(sys.argv) not in (2, 3):
            print("Usage: python test_https_wss.py <device-ip> [port]")
            sys.exit(2)
        host = sys.argv[1]
        port = int(sys.argv[2]) if len(sys.argv) == 3 else 5000
        asyncio.run(main(host, port))

    Run (port 5000 is the default if omitted):

    python test_https_wss.py <device-ip> 5000
    

    Expected results

    Step Pass Fail (original bug)
    HTTPS GET https://<ip>:5000/ status: 200, body: HTTPS OK connection error
    WSS wss://<ip>:5000/ws recv: aaaa OSError: -30464 in server.poll()

    On ESP32-C3: MemoryError at server.start() (HTTPS never starts).

  9. dhalbert commented on Jun 30, 2026

    @dhalbert
    Collaborator

    @berkut0 Thanks! Could you test with 10.3.0-alpha.3? There are some changes since 10.2.1 that might relate to this.

  10. berkut0 commented on Jun 30, 2026

    @berkut0
    Author

    Tested 10.3.0-alpha.3 on my custom ESP32-C3 board (Adafruit QT Py ESP32-C3 firmware). No change vs 10.2.1: same MemoryError in server.start() → _create_server_socket. ws:// still works.

    The original failure mode from this issue (HTTPS up, then OSError: -30464 in server.poll() on WSS, taking down the whole program) no longer happens here — it's replaced by a clear MemoryError before the server starts. That's a better outcome on ESP32-C3.

    It seems to me it might make sense to close #10093 for the C3 case with that note, or perhaps consider a separate issue documenting that ESP32-C3 doesn't have enough RAM for HTTPS/WSS — though you'd probably want to verify on ESP32-S3 first before treating the issue as resolved, which I can't do right now (I'm focused on the C line in general).

    Happy to follow whatever you think fits best.

  11. dhalbert commented on Jun 30, 2026

    @dhalbert
    Collaborator

    It might be possible to adjust the network parameters for the C3 to prevent the memory error; then it would fail in the same way that the S3 is failing.

    it might make sense to close #10093 for the C3 case

    Just to confirm, that is this issue, is that what you meant? I would leave it open for the non MemoryError case. A separate issue would be to see if the params can be adjusted.

  12. berkut0 commented on Jul 2, 2026

    @berkut0
    Author

    Yes, I meant this issue, but I agree it probably should stay open for the non-MemoryError case.

    My current impression from testing on ESP32-C3 is that the original behavior described here is no longer reproduced on recent builds: instead of HTTPS starting and then WSS failing later with OSError: -30464 in server.poll(), the failure now happens earlier and more clearly as a MemoryError during server.start().

    So for the C3 case, this feels like a much better failure mode. My guess is that the original report may have been mostly an ESP32-C3-specific low-memory issue, but I may be wrong — I haven't had time to check this on higher-memory boards yet. My expectation is that on those boards it probably just works.

    A separate issue for trying to tune the network/SSL parameters on ESP32-C3 sounds reasonable to me.

    Thanks a lot for looking into this.

  13. modified the milestones: 10.x.x, 11.0.0 on Sep 28, 2026
  14. self-assigned this
    on Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions