Windows 中的 Python udp 套接字(如果在命令 promt 中运行,则无法将消息发送到服务器(在 IDE 中发送没问题))

标签 python sockets udp

我的 python 应用程序中存在套接字通信问题。我用的是python32。操作系统 Windows 7。 在我的任务中,我必须使用 UDP 套接字。如果我从 IDE(Eclipse) 运行我的应用程序,客户端和服务器之间的通信就很好。

但是: 如果我在命令提示符中运行我的应用程序,然后我无法从客户端到服务器进行通信(获取 errno 11004 getaddrinfo 失败)。在 Windows XP 上应用程序工作正常。 我正在尝试关闭防火墙,但没有帮助。 为什么我无法从 cmd 进行通信?

客户端连接:

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(15)
except socket.error as msg:
    print(msg)
    s.close()
    s = None

addr=(HOST,int(PORT))
msg="CONNECT"
s.sendto(bytes(msg,"ascii"),addr)
try:
    data = s.recvfrom(1024)[0]
except socket.timeout as err:
    print("Connection lost! /cry")
    sys.exit(1)

和服务器代码:

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error as msg:
    print(msg)
    s = None

s.settimeout(45)
s.bind(('0.0.0.0',PORT))

if s is None:
    print('could not open socket')
    sys.exit(1)
print("Server created. Waiting for player.")
sost = "Server"
while True:
    try:
        (data,addr) = s.recvfrom(1024)
    except socket.timeout as err:
        print("Nobody want's to connect! /cry")
        sys.exit(1)

    if data == b"CONNECT":
        print("User from {0} connected".format(addr))
        s.sendto(b"CONNECT_OK",addr)
    break;

PS:抱歉我的英语:)

最佳答案

当你得到异常时,你能打印出addr变量的值吗?也许地址有些愚蠢(嵌入换行或类似的东西)

添加 addr.strip() 调用可能最安全?

关于Windows 中的 Python udp 套接字(如果在命令 promt 中运行,则无法将消息发送到服务器(在 IDE 中发送没问题)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218151/

相关文章:

c - udp 套接字上的多个变量

python - 在 Python 中查询现有套接字的地址族

networking - 是否有针对udp打洞的安全措施?

linux - 为什么这个 UDP 客户端/服务器代码不起作用?

c - 如何控制UDP套接字的吞吐量?

python - 获取 Soundcloud 桌面应用程序的访问 token ?

__main__ 中的 Python getopt()

原始输入多行字符串时python运行时错误

python - 如何根据变量选择数据框中的列范围?

Python 3.4 输入?