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

python-ecosys/aiohttp ignores 'headers' argument for websocket #940

Open
jomasnash opened this issue Nov 30, 2024 · 3 comments
Open

python-ecosys/aiohttp ignores 'headers' argument for websocket #940

jomasnash opened this issue Nov 30, 2024 · 3 comments

Comments

@jomasnash
Copy link

jomasnash commented Nov 30, 2024

Problem:

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
Copy link
Author

Update:

Changing the following two lines will solve the problem:

In __init__.py (line 266), add 'self._base_headers' as argument

async def _ws_connect(self, url, ssl=None):
    ws_client = WebSocketClient(self._base_headers)  # <--- add self._base_headers

And in aiohttp_ws.py (line 139) change:

async def handshake(self, uri, ssl, req):
    # headers = {}  # <--- replace this
    headers = self.params  # <--- by this

Now the example code will work.

@Carglglz
Copy link
Contributor

Carglglz commented Dec 2, 2024

@jomasnash
Nice finding, I see now I missed this use case while developing the WebSocketClient 😓,
would you like to make a PR with the fix?

@jomasnash
Copy link
Author

@Carglglz
I made a PR. (It is the first time ever I made a PR so I hope it is ok.)

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

No branches or pull requests

2 participants