客户端服务端傻傻分不清
在双方的网络通讯中,客户端与服务端的角色并不是划分的很决定,任何一方都可以发送数据,也可以接收数据。
实现一个简易的DNS服务器模型
DNS服务器端
import socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_addr = ("", 8053)
server_sock.bind(server_addr)
# 用来存放域名与ip对应关系的字典
domain_ip = {
"www.itcast.cn": "192.168.1.2",
"www.itheima.com": "192.168.1.3",
"www.google.com": "192.168.1.4",
}
while True:
# 接收用户要查询的域名
receive_data, client_addr = server_sock.recvfrom(1024)
domain = receive_data.decode("utf-8")
print(client_addr, ": ", domain)
# 从字典中获取对应域名的ip地址
ip = domain_ip.get(domain, "i do not know")
# 将ip地址返回给客户端
server_sock.sendto(ip.encode("utf-8"), client_addr)
客户端
import socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_addr = ('127.0.0.1', 8053)
domain = input("请输入要查询的域名:")
while domain:
# 向服务端发送要查询的域名
client_sock.sendto(domain.encode("utf-8"), server_addr)
# 接收服务端发送过来的ip信息
ip = client_sock.recv(1024)
print(ip.decode("utf-8"))
domain = input("请输入要查询的域名:")
client_sock.close()