我正在关注《 Python网络编程基础》一书。它有一个UDP服务器/客户端可以互相发送消息的示例。这是它的样子
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if 2<= len(sys.argv) <=3 and sys.argv[1] == 'server':
interface = sys.argv[2] if len(sys.argv) > 2 else ''
s.bind((interface, PORT))
print('Listening at {}'.format(s.getsockname()))
while True:
data, address = s.recvfrom(MAX)
print('The client at {} says: {}'.format(address, repr(data)))
msg = 'Your data was {} bytes'.format(len(data))
s.sendto(msg.encode('utf-8'), address)
elif len(sys.argv)==3 and sys.argv[1]=='client':
hostname = sys.argv[2]
s.connect((hostname, PORT))
print('Client socket name is {}'.format(s.getsockname()))
s.send(b'This is another message')
s.settimeout(5.0)
data = s.recv(MAX)
print('The server says', repr(data)) code here
我在本地计算机上启动服务器:
python listing2-2.py server
Listening at ('0.0.0.0', 1060)
然后我运行我的客户端
python listing2-2.py client 127.0.0.1
Client socket name is ('127.0.0.1', 59535)
The server says b'Your data was 23 bytes'
一切都很好。我可以使用本地主机,它也可以。但是如果我使用我的主机名
python listing2-2.py client <myhostname>
Client socket name is ('127.0.0.1', 45677)
,客户端超时。服务器从客户端接收消息(我在服务器端看到输出“ This is another message”),但是客户端似乎拒绝了服务器的消息。我正试图了解原因。