今日内容:
1, tcp协议的聊天
服务器(server):
# 服务器:<br>import socket sk = socket.socket() # 创建 套接字 sk.bind(('127.0.0.1', 9090)) # 绑定 端口 sk.listen()# 监听 flag = True while flag: con, addr = sk.accept() while 1: msg = con.recv(1024).decode('utf-8') print(f'客户端:{addr}发送了:{msg}') if msg == 'q': break anime = input('>>>') con.send(anime.encode('utf-8')) if anime.lower() == 'q': flag = False break con.close() sk.close()
客户端(client):
# 客户端 import socket sk = socket.socket() sk.connect(('127.0.0.1', 9090)) while 1: user = input('>>>') if user.lower() == 'q': break sk.send(user.encode('utf-8')) msg = sk.recv(1024).decode('utf-8') print(msg) if msg == 'q': break sk.close()
阻塞: 让程序停下 堵住.
accept() 等待连接
recv() 等待接收客户端打印的消息
input() 等待用户输入.
socket.socket(family = socket.AF_INET, type = SOCK_STREAM )
参数1: family: 套接字类型
family = socket.AF_INET 采用网络形式通信的套接字
family = socket.AF_UNIX 采用文件形式通信的套接字
参数2 type : 通信协议类型 tcp协议, udp 协议
tcp: SOCK_STREAM
udp: SOCK_DGRAM
2, udp协议的聊天
sk = socket.socket(type=socket.SOCK_DGRAM)
sk.recvfrom
服务器(server):
# 服务器 from socket import socket, SOCK_DGRAM sk = socket(type=SOCK_DGRAM) sk.bind(('127.0.0.1', 9090)) while 1: msg_r, addr = sk.recvfrom(1024) msg_r = msg_r.decode('utf-8') print(f'客户端:{addr},发来消息:{msg_r}') if msg_r.lower() == 'q': continue msg_s = input('>>>') sk.sendto(msg_s.encode('utf-8'), addr) if msg_s.lower() == 'q': break sk.close()
客户端(client):
# 客户端 from socket import socket, SOCK_DGRAM sk = socket(type=SOCK_DGRAM) while 1: msg_s = input('>>>') sk.sendto(msg_s.encode('utf-8'), ('127.0.0.1', 9090)) if msg_s.lower() == 'q': break msg_r, addr = sk.recvfrom(1024) msg_r = msg_r.decode('utf-8') print(f'客户端:{addr},发来消息:{msg_r}') if msg_r.lower() == 'q': break sk.close()
3, 基于udp协议的时间同步机制.
服务器(server):
# 基于 udp协议 的服务器 import socket import time sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',9090)) while 1: tm_format,addr = sk.recvfrom(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)# 返回给客户端 sk.close()
客户端(client):
# 基于 udp 协议 的 客户端 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',9090)) local_tm,addr = sk.recvfrom(1024) print(local_tm.decode('utf-8')) time.sleep(2)
4, 在pycharm上实现着色
' 33[0;32;40m欢迎使用学生选课系统 33[0m' 这是一个字符串, 着色其实就是 用