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

'''recv与recvfrom的区别及基于udp实现ntp服务'''
from socket import *
'''服务端'''

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


udp_server = socket(AF_INET, SOCK_DGRAM)

udp_server.bind(ip_port)
#
# while True:
# data, addr = udp_server.recvfrom(buffer_size) # 可以收到为空的消息
# print(data)
# # msg = input('请输入:')
# udp_server.sendto(data.upper(), addr)
#
# udp_server.close()

# 因为udp没有建立链接这么一说,所以就这样也可以实现并发的效果,多个客户端链接并发送消息都可以处理,而tcp一次只能处理一个


'''ntp服务'''
import time
while True:
data, addr = udp_server.recvfrom(buffer_size)
if not data:
fmt = '%Y-%m-%d %X'
else:
fmt = data.decode('utf-8')
back_time = time.strftime(fmt) # 输入只要是符合%Y %m %d %X就都可以返回对应的时间及格式
udp_server.sendto(back_time.encode('utf-8'), addr) # 如果数据类型为整型或浮点型,必须先转为字符串,然后再进行编码

udp_server.close()


from socket import *
'''客户端'''

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

udp_client = socket(AF_INET, SOCK_DGRAM)

# while True:
# msg = input('请输入:').strip() # 输入为空时,服务端能收到一个为空的消息,服务端也发送给了一个为空转成大写(也是为空)的消息给客户端;而tcp会阻塞
# udp_client.sendto(msg.encode('utf-8'), ip_port)
# data, addr = udp_client.recvfrom(buffer_size)
# print(data)
#
# udp_client.close()


'''ntp服务'''
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_client.close()


from socket import *
'''客户端1'''

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

udp_client = socket(AF_INET, SOCK_DGRAM)

# while True:
# msg = input('请输入:').strip() # 输入为空时,服务端能收到一个为空的消息,服务端也发送给了一个为空转成大写(也是为空)的消息给客户端;而tcp会阻塞
# udp_client.sendto(msg.encode('utf-8'), ip_port)
# data, addr = udp_client.recvfrom(buffer_size)
# print(data)
#
# udp_client.close()


'''ntp服务'''
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_client.close()
上一篇:电脑校时器(电脑对时器)设置方法介绍


下一篇:windows系统下向NTP服务器请求时间代码 C语言,vs2010,windows,socket,udp