new*_*434 5 python sockets websocket python-3.x
我怎样才能做到这一点
这是我的代码
import websockets
async def test():
async with websockets.connect('ws://iqoption.com') as websocket:
response = await websocket.recv()
print(response)
# Client async code
Run Code Online (Sandbox Code Playgroud)
提示是,我可以发送此标头以在服务器中进行身份验证吗
标头
'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'}
Run Code Online (Sandbox Code Playgroud)
我可以用其他代码做到这一点,但消息仍然用 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("")
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
我认为您目前对 WebSockets 缺乏基本的了解,正如您之前的实验所示。WebSocket 不是普通的套接字。WebSocket 是在 HTTP 握手后创建的一些类似套接字的想法。您不能像您尝试过的那样从连接中获取套接字requests
,但您必须明确使用RFC 6455中定义的 WebSocket 应用程序协议。
也就是说,使用像这样的库websockets
要好得多。但您仍然必须使用实际的 WebSocket 端点作为目标,而不仅仅是同一服务器上的某个任意 URL。在这种情况下,端点不是
ws://iqoption.com
but wss://iqoption.com/echo/websocket
,即更长的路径 andwss://
而不是ws://
。
如果没有正确的 URL,您会收到错误消息,您似乎会将其解释为身份验证问题。但这里根本不涉及身份验证。一旦您使用正确的端点,它就可以正常工作,无需发送特定的标头:
async def test():
async with websockets.connect("wss://iqoption.com/echo/websocket") as websocket:
response = await websocket.recv()
print(response)
Run Code Online (Sandbox Code Playgroud)