python之路第八编_Socket_2
python动态导入及断言 |
新建一个python包,在里面新建一个类。2、在包的统计目录下新建一个python文件,导入python包里面的内容。并断言此结果是否为字符串。具体如下所示:
1 class dog(object): 2 def __init__(self): 3 self.name ="haha"
1 import importlib 2 aa = importlib.import_module("lib.aa") 3 print(aa.dog().name) 4 5 assert type(aa.dog().name) is str #断言他是字符串,才能执行后面的内容 6 7 print("aa")
在复习python3编码的问题 |
在python3中默认的编码为字节码,即bytes。在数据传输中必须为二进制格式,所以必须强制转换成uncode格式。
UTF-8编码:是对Unicode 编码的压缩和优化,他不再使用最少2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存。
如下为转换方式
Socket配置 |
1 import socket 2 3 client = socket.socket() #声明socket类型,同时生成socket连接对象 4 #client.connect(('192.168.16.200',8888)) 5 client.connect(('localhost',8888)) 6 while True: 7 msg = input(">>:").strip() 8 if len(msg) == 0:continue 9 client.send(msg.encode("utf-8")) 10 data = client.recv(10240) 11 12 print("recv:",data.decode()) 13 14 client.close()
1 import socket 2 import os,hashlib 3 client =socket.socket() 4 client.connect(("localhost",9990)) 5 while True: 6 cmd = input(">>:").strip() 7 if len(cmd) ==0:continue 8 if cmd.startswith("get"): 9 client.send(cmd.encode()) 10 server_response = client.recv(1024) 11 print("server response:",server_response) 12 client.send(b"ready to recv file") 13 file_total_size = int(server_response.decode()) 14 recived_size = 0 15 filename = cmd.split()[1] 16 f =open(filename+".new","wb") 17 m = hashlib.md5() 18 while recived_size <file_total_size: 19 if file_total_size -recived_size >1024: 20 size =1024 21 else: 22 size = file_total_size -recived_size 23 print("last receive:",size) 24 data = client.recv(size) 25 recived_size +=len(data) 26 m.update(data) 27 f.write(data) 28 else: 29 new_file_md5 = m.hexdigest() 30 print("file recv done",recived_size,file_total_size) 31 f.close() 32 server_file_md5 = client.recv(1024) 33 print("sever file md5:",server_file_md5) 34 print("client file md5:",new_file_md5) 35 36 client.close()