[toc]
---
使用使用`socke`t进行`udp`通信, 输入"close"后关闭
#### 一、服务端代码`UdpServer.py`
```
from socket import *
from time import ctime
# 创建socket, SOCK_DGRAM 指定的是datagram(UDP)
udp_socket = socket(AF_INET, SOCK_DGRAM)
hostname = "192.168.0.58" # 主机地址
print("localhost: ", hostname)
port = 12345
udp_socket.bind((hostname, port)) # 绑定socket到本地地址
while True:
print("server等待接收数据...")
data, address = udp_socket.recvfrom(1024) # 此方法类似于recv(buffersize, flags), 但是返回地址信息
data = data.decode("utf-8")
print("server接收到数据: %s" % data)
if "close" in data:
udp_socket.sendto("server关闭".encode("utf-8"), address)
break
data = ("server " + ctime()).encode("utf-8")
udp_socket.sendto(data, address)
udp_socket.close()
```
#### 二、客户端代码`UdpClient.py`
```
from socket import *
host = "192.168.0.58" # 服务端主机地址
port = 12345 # 服务端端口
udp_socket = socket(AF_INET, SOCK_DGRAM)
while True:
data = input("输入要发送的内容:")
if data:
udp_socket.sendto(data.encode("utf-8"), (host, port))
print("client已发送数据:%s" % data)
data, addr = udp_socket.recvfrom(1024)
data = data.decode("utf-8")
print("client接收到的数据:%s" % data)
if "close" in data:
break
udp_socket.close()
```