tcp协议聊天
服务端::
客户端
udp协议的聊天
############ udp协议 ########### 服务器 import socket sk = socket.socket(type = socket.SOCK_DGRAM) ##udp协议 sk.bind((ip地址,端口号)) while 1: msg_r,addr = sk.recvfrom(1024) ##接收来自哪里的消息 print(msg_r.decode('utf-8'),addr) ##把收到的内容解码出来 if msg_r.decode('utf-8') == 'q': continue user = input('>>>') sk.sendto(user.encode('utf-8'),addr) if user == 'q': break sk.close() 客户端: import socket sk = socket.socket(type = socket.SOCK_DGRAM) while 1: mag = input('>>>>') sk.sendto(mag.encode('utf-8')(服务器ip地址,服务器那边的端口号) if mag == 'q': break mag_r,addr = sk.recvfrom(1024) print(mag_r.decode(''utf-8)) if mag_r.decode() == 'q': break
################ 时间同步机制 #################### 服务器: import socket ##引进socket模块 import time ##引进时间模块 sk = socket.socket(type = socket.SOCK_DGRAM) ##实例化 DGRAM 是udp 这个位置是固定的 sk.bind(ip地址,端口号) while 1: tm_format,addr = sk.recvfrom(1024) ##接收的是1024个字节 tm_format = tm_format.decode('utf-8') ##%Y/%m/%d %H:%M:%S local_tm = time.strftime(tm_format) ##获取到了对应格式的当前时间 sk.sendto(local_tm.encode('utf-8'),addr) ##返回给客户端 客户端: import socket ##引入socket模块 import time ##引入time模块 sk = socket.socket(type = socket.SOCK_DGRAM) ##udp协议固定的 tm_format = input('>>>') ##输入 while 1: sk.sendto(tm_format.encode('utf-8'),(ip地址,端口号)) ##发送出去 local_tm,addr = sk.recvfrom(1024) ##接收1024个字节 print(local_tm,decode('utf-8')) ##解码 time.sleep(2) ##停顿2秒