33 udp协议编码 显示客户端名字,输出带颜色的内容 udp协议的时间同步机制 #一.udp 协议编码 一个服务器,多个客户端 #服务器: # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # sk.bind(("127.0.0.1",8801)) # while True: # msg,addr=sk.recvfrom(1024) # print(msg.decode("utf-8"),addr) # msg1=msg.decode("utf-8") # if msg1=="q": # continue # con=input("<<<").encode("utf-8") # sk.sendto(con,addr) # if con =="q": # break # sk.close() #客户端 # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # while True: # con1=input("<<<").encode("utf-8") # sk.sendto(con1,("127.0.0.1",8801)) # if con1=="q": # break # msg_c,addr=sk.recvfrom(1024) # print(msg_c.decode("utf-8")) # msg2=msg_c.decode("utf-8") # if msg2=="q": # break # sk.close() # 二.优化代码显示客户端名字 #服务器 # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # sk.bind(("127.0.0.1",8801)) # while True: # msg,addr=sk.recvfrom(1024) # print(msg.decode("utf-8"),addr) # msg1=msg.decode("utf-8") # if msg1=="q": # continue # con=input("<<<").encode("utf-8") # sk.sendto(con,addr) # if con =="q": # break # sk.close() #客户端 # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # name=input("请输入名字:") # while True: # con1=input("<<<") # con1=name+":"+con1 # sk.sendto(con1.encode("utf-8"),("127.0.0.1",8801)) # if con1=="q": # break # msg_c,addr=sk.recvfrom(1024) # print(msg_c.decode("utf-8")) # msg2=msg_c.decode("utf-8") # if msg2=="q": # break # sk.close() #三.输出带颜色的字(一个客户端) #服务器: # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # sk.bind(("127.0.0.1",8801)) # while True: # msg,addr=sk.recvfrom(1024) # msg_c=msg.decode("utf-8") # print("\033[0;35;41m%s,%s\033[0m"%(msg_c,addr)) # # if msg_c=="q": # continue # con=input("<<<").encode("utf-8") # sk.sendto(con,addr) # if con =="q": # break # sk.close() #四.输出带颜色的文字( 一个服务器 多个客户端) #服务器 # import socket # sk=socket.socket(type=socket.SOCK_DGRAM) # sk.bind(("127.0.0.1",8801)) # dic={"alex":"\033[0;35;41m","太白":"\033[0;32;40m"} # while True: # msg,addr=sk.recvfrom(1024) # msg_c=msg.decode("utf-8") # name=msg_c.split(":")[0].strip() # print(name) # color=dic.get(name,"") # print("%s%s\033[0m" % (color,msg_c)) # # if msg_c=="q": # continue # con=input("<<<").encode("utf-8") # sk.sendto(con,addr) # if con =="q": # break # sk.close() #五.基于udp协议的时间同步机制 #服务器 # import socket # import time # sk=socket.socket(type=socket.SOCK_DGRAM) # sk.bind(("127.0.0.1",8801)) # while 1: # tm_format,addr=sk.recvfrom(1024) # tm_format=tm_format.decode("utf-8") # local_time=time.strftime(tm_format) # sk.sendto(local_time.encode("utf_8"),addr) # sk.close() #客户端 # import socket # import time # sk=socket.socket(type=socket.SOCK_DGRAM) # tm_format=input(">>>") # while 1: # sk.sendto(tm_format.encode("utf-8"),("127.0.0.1",8801)) # local_time,addr=sk.recvfrom(1024) # print(local_time.decode("utf-8")) # time.sleep(5) #五秒出一个 # sk.close()