Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aiohttp: fix header problem #941

Merged
merged 1 commit into from
Apr 12, 2025

Conversation

jomasnash
Copy link
Contributor

Latest version of aiohttp:
When making connection to a Websocket, the header argument is ignored.

The consequence is that you cannot make a connection to most online MQTT broker's over websocket
because they need the header entry: "Sec-WebSocket-Protocol":"mqtt" in the handshake of
the upgrade protocol.

See this small example code:
It connects to a MQTT broker and then sends the CONNECT mqtt packet.
Then it should get a reply of opcode:2, data: b' \x02\x00\x00' where 'data' is a CONNACK mqtt package
Because of the missing header entry "Sec-WebSocket-Protocol":"mqtt" most brokers will refuse the connection or
refuse to accept MQTT packets.

import aiohttp
import asyncio

async def connect():
    url = "ws://test.mosquitto.org:8080"
    headers = {"Sec-WebSocket-Protocol":"mqtt"}
    connect_pkt = bytearray(b'\x10\x10\x00\x04MQTT\x04\x02\x00x\x00\x04fz54')
    
    async with aiohttp.ClientSession(headers=headers).ws_connect(url) as ws:
            print("Connected")
            await ws.send_bytes(connect_pkt)
            opcode, data = await ws.ws.receive()
            print(f"opcode:{opcode}, data{data}")

asyncio.run(connect())

@jomasnash jomasnash changed the title fix header problem aiohttp: fix header problem Dec 2, 2024
@Carglglz
Copy link
Contributor

Carglglz commented Dec 5, 2024

I've just tested this and it works as expected, hopefully it is merged for the next release, thanks! 👍🏼

This commit will make it possible to add headers to a Websocket.

Among other things, this allows making a connection to online MQTT brokers
over websocket, using the header entry "Sec-WebSocket-Protocol":"mqtt" in
the handshake of the upgrade protocol.

Signed-off-by: Damien George <[email protected]>
@dpgeorge dpgeorge force-pushed the micropython-lib-fix branch from c329e83 to 05a56c3 Compare April 12, 2025 14:24
@dpgeorge
Copy link
Member

Thanks for updating. I tested the example code above and it works with this PR.

@dpgeorge dpgeorge merged commit 05a56c3 into micropython:master Apr 12, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants