python-3.xwebsocketpython-asynciohttp-proxy

client websocket connect through proxy


I'm using the websockets module, but it doesn't support connecting though my corporate proxy for a client connection:

>>> import asyncio, websockets
>>> async def connect(uri):
...     async with websockets.connect(uri) as websocket:
...         pass
...
>>> asyncio.get_event_loop().run_until_complete(connect('ws://myhost.com/path/'))
    ....
ConnectionRefusedError: [Errno 10061] Connect call failed ('myhost.com', 80)

However if use curl with my http_proxy env var set, it works:

$ curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" -H "Sec-WebSocket-Key: MTIzNDEyMzQxMjM0MTIzNA==" http://myhost.com/path/
HTTP/1.1 101 Switching Protocols
Server: nginx/1.13.6
Date: Fri, 10 Nov 2017 14:51:00 GMT
Upgrade: websocket
Sec-WebSocket-Accept: s+CT5bkW5F3N2/5JUXrCPtLHn68=
Connection: Upgrade

What are my best options? Some other module for making client-websocket connects?


Solution

  • Use pip install websocket-client. Then place your http*_proxy variables in os.environ as you normally do. Code like so:

    ws = websocket.create_connection('ws://example.com/path')
    ws.send(out_data)
    in_data = ws.recv()
    

    If you don't know exactly what protocols your proxy uses, set up both http*_proxy variables like this example:

    $ export http_proxy=http://jonasb:password@proxyserver:8000
    $ export https_proxy=https://jonasb:password@proxyserver:8000
    

    (assuming your username is jonasb, and port is 8000).