server.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
sock = socket.socket(type=socket.SOCK_DGRAM) # 创建socket对象,注意参数
sock.bind(('127.0.0.1', 8002)) # 绑定ip
while True:
client_msg, address = sock.recvfrom(1024)
print('收到客户端的数据: ', client_msg.decode())
sock.sendto('udp server'.encode(), address)
client.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
sock = socket.socket(type=socket.SOCK_DGRAM)
while True:
msg = input('输入信息: ')
sock.sendto(msg.encode(), ('127.0.0.1', 8002))
server_msg, address = sock.recvfrom(1024)
print('接收到的服务端的数据: ', server_msg.decode())
sock.close()