简体   繁体   中英

How to send 'Headers' in websocket python

how can i make this

This is my code


import  websockets


async def test():
    async with websockets.connect('ws://iqoption.com') as websocket:
        response = await websocket.recv()
        print(response)
# Client async code

The cuestion is, can i send this headers to get Authenticated in the server

Headers

    'Host':'iqoption.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0',
    'Accept' : '*/*',
'Accept-Encoding': 'gzip, deflate',
'Sec-WebSocket-Version' : '13',
'Origin' : 'https://iqoption.com',
    'Sec-WebSocket-Key': 'iExBWv1j6sC1uee2qD+QPQ==',
'Connection' : 'keep-alive, Upgrade',
'Upgrade': 'websocket'}

I could do it with this other code but the messages were still encrypted with tls

proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
urllib3.disable_warnings()

r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers, proxies=proxies, verify=False)
#r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers)
s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)


def receive_and_print():
    #for message in iter(lambda: s.recv(1024).decode("utf-8", errors="replace"), ''):
    for message in iter(lambda: s.recv(1024).decode( errors="replace"), ''):
        print(":", message)
        print("")
import threading
background_thread = threading.Thread(target=receive_and_print)
background_thread.daemon = True
background_thread.start()

while 1:
    s.send(input("Please enter your message: ").encode())
    print("Sent")
    print("")

Any advice??

I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to explicitly speak the WebSocket application protocol, defined in RFC 6455 .

That said, using a library like websockets is much better. But you still have to use the actual WebSocket endpoint as target and not just some arbitrary URL on the same server. The endpoint in this case is not ws://iqoption.com but wss://iqoption.com/echo/websocket , ie a longer path and wss:// instead of ws:// .

Without the proper URL you get error messages you seem to interpret as authentication problems. But there is no authentication involved here at all. Once you use the proper endpoint it simply works without any need to send specific headers:

async def test():
    async with websockets.connect("wss://iqoption.com/echo/websocket") as websocket:
        response = await websocket.recv()
        print(response)

I think you can directly add headers in the request. Here's my example using websockets .

async def hello(uri):
    async with websockets.connect(uri=uri, extra_headers= {'Auth':'yourTokenHere'}) as websocket:
        await websocket.send(json.dumps({"action":"hello", "message":"hi"})) # AWS.APIGateway style for example
        message = await websocket.recv()

Btw, the way I figured out about the extra_headers is but directly checking the code here . And they do have a good documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM