recv和recvfrom的区别及基于udp实现ntp服务

udp_server

from socket import *
import time

ip_port = ('127.0.0.1', 8080)
buf_size = 1024

udp_server = socket(AF_INET, SOCK_DGRAM)
udp_server.bind(ip_port)

while True:
    data, addr = udp_server.recvfrom(buf_size)
    if not data:
        fmt = '%Y-%m-%d %X'
    else:
        fmt = data.decode(encoding='utf-8')

    udp_server.sendto(time.strftime(fmt).encode('utf-8'), addr)

udp_client

from socket import *

ip_port = ('127.0.0.1', 8080)
buf_size = 1024

udp_client = socket(AF_INET, SOCK_DGRAM)

while True:
    msg = input('>>')
    udp_client.sendto(msg.encode(encoding='utf-8'), ip_port)

    data, addr = udp_client.recvfrom(buf_size)
    print(data.decode(encoding='utf-8'))

你可能感兴趣的:(python)