时间服务器

server端

# 需求
    # 写一个时间同步的服务器
    # 服务端接收请求
    # 按照client端发送的时间格式,将服务器时间转换成对应格式
    # 发送给客户端
import time
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',9000))
while True:
    msg,addr = sk.recvfrom(1024)
    # msg 客户端发送给server端的时间格式 "%Y-%m-%d %H:%M-%S"
    time_format = msg.decode('utf-8')
    time_str = time.strftime(time_format)
    sk.sendto(time_str.encode('utf-8'),addr)
sk.close()

client端

# client端每隔一段时间发送请求到服务端
# 发送时间的格式
import time
import socket
import os
sk = socket.socket(type = socket.SOCK_DGRAM)
while True:
    sk.sendto('%Y-%m-%d %H:%M:%S'.encode('utf-8'),('127.0.0.1',9000))
    msg,addr = sk.recvfrom(1024)
    print(msg.decode('utf-8'))
    time.sleep(10)
    os.system('cls')
sk.close()

# while True + time.sleep的形式

 

posted @ 2018-09-02 16:07  Woowo  阅读(163)  评论(0编辑  收藏  举报