UDP套接字

		##############udp套接字编程#################
			###服务端端:
				from socket import  *
				ip_port=('127.0.0.1',8090)
				buffer_size=1024
				udp_server=socket(AF_INET,SOCK_DGRAM)
				udp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
				udp_server.bind(ip_port)
				while True:
				    data,addr=udp_server.recvfrom(buffer_size)
				    print('接收到来自客户端的数据是',data,addr)
				    udp_server.sendto(data.upper(),addr)
			###客户端:
				from socket import  *
				ip_port=('127.0.0.1',8090)
				buffer_size=1024
				udp_client=socket(AF_INET,SOCK_DGRAM)
				while True:
				    msg=input('请输入>>').strip()
				    udp_client.sendto(msg.encode('utf-8'),ip_port)
				    data,addr=udp_client.recvfrom(buffer_size)
				    print(data.decode('utf-8'))

 

使用udp创建ntp服务器:

###ntp服务端
from socket import  *
import  time
ip_port=('127.0.0.1',8090)
buffer_size=1024
ntp_server=socket(AF_INET,SOCK_DGRAM)
ntp_server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
ntp_server.bind(ip_port)
while True:
    data,addr=ntp_server.recvfrom(buffer_size)
    print('接收到来自客户端的数据是',data,addr)

    if not data:
        fmt = '%Y-%m-%d,%X'
    else:
        fmt=data.decode('utf-8')
    back_time = time.strftime(fmt)

    ntp_server.sendto(back_time.encode('utf-8'),addr)
###ntp客户端
from socket import  *
ip_port=('127.0.0.1',8090)
buffer_size=1024
ntp_client=socket(AF_INET,SOCK_DGRAM)
while True:
    msg=input('请输入>>').strip()
    ntp_client.sendto(msg.encode('utf-8'),ip_port)
    data,addr=ntp_client.recvfrom(buffer_size)
    print('当前的ntp标准时间为;',data.decode('utf-8'))

 

你可能感兴趣的:(编程,ntp,python)