Hello! I am trying to connect to a websocket server via a http proxy using asyncio but running into some issues. The code works fine when I remove the proxy flag in the WebsocketClientFactory. However, with the proxy flag, the client seems to ignore the proxy url altogether and hit the server directly via a HTTP Connect request. Are there any examples of how to use asyncio + websockets with a proxy I can take a look at?
Also is connecting via WSS through a HTTP proxy supported when using asyncio?
Below is the code, any help would be appreciated.
from autobahn.asyncio.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
class MyClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {0}".format(response.peer))
def onOpen(self):
print("WebSocket connection open.")
def hello():
self.sendMessage("Hello, world!".encode('utf8'))
self.sendMessage(b"\x00\x01\x03\x04", isBinary=True)
self.factory.loop.call_later(1, hello)
# start sending messages every second ..
hello()
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
def onClose(self, wasClean, code, reason):
print(self)
print("WebSocket connection closed: {0}".format(reason))
async def onPing(self, payload):
"""
When receiving ping message from spacebridge
"""
print("Received ping")
async def onPong(self, payload):
""" When receiving pong message from spacebridge
"""
print("Received Pong")
self.sendPong()
if __name__ == '__main__':
proxy = {'host': '127.0.0.1', 'port': 8080}
factory = WebSocketClientFactory("ws://127.0.0.1:9000", proxy=proxy)
factory.protocol = MyClientProtocol
loop = asyncio.get_event_loop()
coro = loop.create_connection(factory, '127.0.0.1', 9000)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()