socketserver模块 UDP 的基本使用 UDP实现简易版本的QQ 异常处理 上传视频文件
socketserver模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket client = socket.socket() client.connect(('127.0.0.1',8080)) while True: client.send(b'hello') data = client.recv(1024) print(data.decode('utf-8'))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): # print('来啦 老弟') while True: data = self.request.recv(1024) print(self.client_address) # 客户端地址 print(data.decode('utf-8')) self.request.send(data.upper()) if __name__ == '__main__': """ 只要有客户端连接 会自动交给自定义类中的handle方法去处理 """ server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) # 创建一个基于TCP的对象 server.serve_forever() # 启动该服务对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket import time client = socket.socket(type=socket.SOCK_DGRAM) server_address = ('127.0.0.1',8080) while True: client.sendto(b'hello',server_address) data,addr = client.recvfrom(1024) print(data.decode('utf-8'),addr) time.sleep(1)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): # print('来啦 老弟') while True: data,sock = self.request print(self.client_address) # 客户端地址 print(data.decode('utf-8')) sock.sendto(data.upper(),self.client_address) if __name__ == '__main__': """只要有客户端连接 会自动交给自定义类中的handle方法去处理""" server = socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyServer) # 创建一个基于TCP的对象 server.serve_forever() # 启动该服务对象
UDP 的基本使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket client = socket.socket(type=socket.SOCK_DGRAM) # 不选压迫建立连接 直接进入通信循环 server_address = ('127.0.0.1',8080) while True: client.sendto(b'hello',server_address) data,addr = client.recvfrom(1024) print('服务端发来的数据',data) print('服务端的地址',addr)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket server = socket.socket(type=socket.SOCK_DGRAM) server.bind(('127.0.0.1',8080)) while True: data,addr = server.recvfrom(1024) print('数据',data) print('地址',addr) server.sendto(data.upper(),addr)
UDP实现简易版本的QQ
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket server = socket.socket(type=socket.SOCK_DGRAM) server.bind(('127.0.0.1',8080)) while True: data,addr = server.recvfrom(1024) print(data.decode('utf-8')) msg = input('>>>:') server.sendto(msg.encode('utf-8'),addr)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket client = socket.socket(type=socket.SOCK_DGRAM) server_address = ('127.0.0.1',8080) while True: msg = input('>>>:') msg = '来自客户端 1 的消息:%s' %msg # 根据客户端序号将内容进行修改 client.sendto(msg.encode('utf-8'),server_address) data,server_addr = client.recvfrom(1024) print(data.decode('utf-8'))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket client = socket.socket(type=socket.SOCK_DGRAM) server_address = ('127.0.0.1',8080) while True: msg = input('>>>:') msg = '来自客户端2 的消息:%s' %msg client.sendto(msg.encode('utf-8'),server_address) data,server_addr = client.recvfrom(1024) print(data.decode('utf-8'))
客户端可以加很多 将内容稍微修改就行
异常处理
异常
res = {'name':''} print(res) print(res.get('pwd','asd')) int('asd') # ValueError l = [1,2,3,4] l[11] # IndexError
异常处理
try: name l = [1,2,3] l[11] d = {'name':'james'} d['pwd'] except NameError: print('NameError 错 误') except IndexError: print('Indexerror 错 误') except KeyError: print('Keyerror 错 误') # 错误发生之后 会立刻停止代码运行 执行except 对比错误类型
万能异常处理
try: name l = [1,2,3] l[11] d = {'name':'james'} d['pwd'] except Exception: # Exception 万能一场 所有的异常都能捕获 print('出错了')
except 和else finally连用
try: name l = [1,2,3] l[111] d = {'name':'jason'} d['password'] except Exception: # 万能异常 所有的异常类型都被捕获 print('老子天下无敌') else: print('被检测的代码没有任何的异常发生 才会走else') finally: print('
主动抛异常
cmd = input('>>>:') if cmd == 'xxx': pass else: raise TypeError('你说的对')
# 关键字raise就是主动抛出异常
自定义异常
class MyError(BaseException): def __init__(self,msg): super().__init__() self.msg = msg def __str__(self): return '<asdasdasdasd %s asdasd>' %self.msg raise MyError('我自己定义的异常') #主动抛出异常其实就是将异常类的对象打印处理啊 会走__str__方法
上传视频文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket,json,os,struct client = socket.socket() client.connect(('127.0.0.1',8080)) while True: # 获取电影列表 MOVIE = r'E:\笔记\day01\视频' movie_list = os.listdir(MOVIE) # print(movie_list) for index,movie in enumerate(movie_list,1): print(index,movie) # 用户选择 choice = input('输入选择的视频顺序号') # 判断是否是数字 if choice: # 将输入字符串转为数字 choice = int(choice) - 1 # 判断用户选择在不在列表范围内 if choice in range(len(movie_list)): # 获取文件上传路径 path = movie_list[choice] # 拼接文件路径 file_path = os.path.join(MOVIE,path) # 获取文件大小 file_size = os.path.getsize(file_path) # 定义一个字典 dic = {'file_name':'这很刺激.mp4','file_size':file_size,'msg':'控制住自己的双手'} # 序列化字典 json_dic = json.dumps(dic) json_bytes = json_dic.encode('utf-8') # 字典报头 header = struct.pack('i',len(json_bytes)) # 发送字典报头 client.send(header) # 再次发送字典 client.send(json_bytes) # 最终发真实数据(打开文件循环发送) with open(file_path,'rb') as f: for line in f: client.send(line) else: print('输入正确序号') else: print('请输入数字')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import socket,json,struct server = socket.socket() server.bind(('127.0.0.1',8080)) # 必须元组87TypeError: getsockaddrarg: AF_INET address must be tuple, not str server.listen(5) while True: conn,addr = server.accept() while True: try: header_len = conn.recv(4) # 解析字典报头 header_len = struct.unpack('i',header_len)[0] # 接受字典数据 header_dic = conn.recv(header_len) real_dic = json.loads(header_dic.decode('utf-8')) # 获取数据长度 total_size = real_dic.get('file_size') # 循环写入文件 recv_size = 0 with open(real_dic.get('file_name'),'wb') as f: while recv_size < total_size: data = conn.recv(1024) f.write(data) recv_size += len(data) print('上传成功') except ConnectionResetError: print('ConnectionResetError 错误') break conn.close()