2017-10-13 158 views
0

Server代码:Python的插座 - 客户没有收到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 

回答

2

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

试试这个:

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

谢谢主席先生。我假设客户端代码为's.connect((socket.gethostname(),9999))'将配置客户端套接字在端口9999上接收,客户端代码为's.sendto(message,(socket.gethostname(),9999 ))会将套接字配置为发送到端口9999 ......如果它没有配置接收端口并且sendto()处理目标端口,你能说明为什么'connect()'中的地址是必需的吗? – aweeeezy

+0

其实,我只是回答了我自己的问题 - 删除'connect()'行不会影响我的程序。 – aweeeezy