从客户端连接到WebSocket服务器时出错

8aqjt8rx  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(238)

我正在尝试使用Python通过WebSocket与Web服务器建立连接。然而,我总是无法做到这一点,因为我不断得到错误:[Errno 11001] getaddrinfo失败
知道是哪里出了问题吗以及如何解决这个问题。谢谢你。
这是我的client.py代码,它应该通过WebSocket连接到Web服务器:

import asyncio
import websockets
from websockets.sync.client import connect

def connection():
    with connect("ws://http://<ip address>") as ws:
        ws.send("Hello world!")
        message = ws.recv()
        print(f"Received: {message}")

if __name__ == "__main__":
    connection()

以下是错误消息:

line 14, in <module>
    connection()

line 7, in connection
    with connect("ws://http://<ip address>/") as ws:

line 247, in connect
    sock = socket.create_connection(

line 824, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):

line 955, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed
rjee0c15

rjee0c151#

“getaddrinfo failed”消息表示主机名无法解析。看看这里的例子https://websockets.readthedocs.io/en/stable/,你不需要在URL中添加“http://”字符串。他们的示例显示了以下连接:

def hello():
with connect("ws://localhost:8765") as websocket:
    websocket.send("Hello world!")
    message = websocket.recv()
    print(f"Received: {message}")

相关问题