python 27 days
python 27 days
1、解决一下怎么让服务器可以和多个客户端连接通信
2、学习udp协议
3、炫酷技能,可以在pycharm中打印带颜色的信息
4、时间同步的机制
知识点:
1、tcp协议,不允许在同一时间点同时和多个客户端连接通信
2、udp协议,允许在同一个时间点同时和多个客户端连接通信
UDP知识点:
upd_服务器
import socket ju = socket.socket(type=socket.SOCK_DGRAM) li = {'光头':'\033[1;23;38m','liuyang':'\033[2;36;40'} ju.bind(('127.0.0.1',8080)) # while True: msg_r,addr = ju.recvfrom(1024) msg_r = msg_r.decode('utf-8') name = msg_r.split(':')[0] color = li.get(name,'') print('%s %s \033[0m'%(color,msg_r)) msg_s = input('>>>:').encode('utf-8') ju.sendto(msg_s,addr) ju.close()
udp_客户端
import socket ju = socket.socket(type=socket.SOCK_DGRAM) name = input('请输入你的名字:>>>') while True: msg_s = input('>>>:') if msg_s == 'q': break ju.sendto((name+':'+msg_s).encode('utf-8'),('127.0.0.1',8080)) msg_r,addr = ju.recvfrom(1024) if msg_r.decode('utf-8') == 'q': break print(msg_r.decode('utf-8')) ju.close()
TIME知识点:
time_服务器
import socket import time ju = socket.socket(type=socket.SOCK_DGRAM) ju.bind(('127.0.0.1',8080)) while True: tm_format,addr = ju.recvfrom(1024) time_now = time.strftime(tm_format.decode('utf-8')) print(time_now) ju.sendto(time_now.encode('utf-8'),addr) ju.close()
time_客户端
import socket import time ju = socket.socket(type=socket.SOCK_DGRAM) print('%Y 年' '%m 月' '%d 日' '%H 时' '%M 分' '%S 秒') tm_format = input('请输入时间格式:') while True: ju.sendto(tm_format.encode('utf-8'),'127.0.0.1',8080) tm_now,addr = ju.recvfrom(1024) print(tm_now.decode('utf-8')) time.sleep(3) ju.close()
socket的对象参数说明:
套接字: