1、UDP的服务器编程步骤:
①.创建一个socket,用函数socket()
②.绑定IP地址、端口等信息到socket上,用函数bind()
③.循环接收数据,用函数recvfrom()
④.关闭网络连接
2、UDP的客户端编程步骤:
①.创建一个socket,用函数socket()
②.绑定IP地址、端口等信息到socket上,用函数bind()
③.设置对方的IP地址和端口等属性
④.发送数据,用函数sendto()
⑤.关闭网络连接
代码:
客户端:
from socket import *
HOST = '119.45.115.128'
PORT = 3555
BUFSIZ = 1024
ADDR = (HOST, PORT)
udpClientSocket = socket(AF_INET, SOCK_DGRAM)
while True:
try:
data = input('>')
print('send the data: ' + data)
msg = data.encode('utf-8')
# 发送数据:
udpClientSocket.sendto(msg, ADDR)
# 接收数据:
print('receive the reply: ' + udpClientSocket.recv(BUFSIZ).decode('utf-8'))
except Exception as e:
print(e)
udpClientSocket.close()
服务端:
from socket import *
from time import ctime
HOST = ''
PORT = 3555
BUFSIZ = 1024
ADDR = (HOST, PORT)
udpServerSocket = socket(AF_INET, SOCK_DGRAM)
udpServerSocket.bind(ADDR)
while True:
try:
data, addr = udpServerSocket.recvfrom(BUFSIZ)
print('来自主机 %s,端口: %s.' % addr)
print(data.decode('utf-8'))
reply = 'Hello, this is udpserver!'
udpServerSocket.sendto(reply.encode('utf-8'), addr)
except Exception as e:
print(e)
udpServerSocket.close()