Python套接字 - 客户端不接收UDP数据报

时间:2017-10-13 19:13:11

标签: python sockets udp

服务器代码:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # server UDP socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bypass OS lock on port
s.bind((socket.gethostname(), 9999)) # bind socket to host and port 9999
while True:
    message, ip = s.recvfrom(1024) # receive data passed through socket
    print "Server:\n\tMessage \"{}\" received...\n\tIt has a length of {}".format(
            message, len(message))
    s.sendto(str(len(message)), (socket.gethostname(), 9999)) # send message length in bytes back to client
    s.close() # close UDP connection with client
    sys.exit(0) # terminate server process

客户代码:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((socket.gethostname(), 9999))
message = "Pointless text."
print "Client:\n\tSending message \"{}\" to the server...\n\tIt has a length of {}".format(
        message, len(message))
s.sendto(message, (socket.gethostname(), 9999))
while True:
    response, ip = s.recvfrom(1024)
    if int(response) == len(message):
        print "Client:\n\tThe server returned count {} which is equal to the client's count of {}.".format(response, len(message))
    else:
        print "Client:\n\tThe server returned count {} which is not equal to the client's count of {}.".format(response, len(message))
s.close()

输出:

Running client in UDP mode...
Running server in UDP mode...

Client:
    Sending message "Pointless text." to the server...
    It has a length of 15
Server:
    Message "Pointless text." received...
    It has a length of 15

客户端recvfrom永远不会被触发,我无法弄清楚原因。

以下是完整的clientserver文件,如果您想直接在您的计算机上测试它们,请执行以下操作:

python2.7 server udp & python2.7 client udp

1 个答案:

答案 0 :(得分:2)

在您的服务器代码中,您将结果发送到服务器的地址(9999),而不是客户端(ip)。

试试这个:

s.sendto(str(len(message)), ip) # send message length in bytes back to client