解決socket數據量過大,如何接收數據

import socket import os server=socket.socket() server.bind(('127.0.0.1',6969)) server.listen() while True:#保證能與多個通話 conn,addr=server.accept() print('與',addr,'通話') while True:#保證與某一個一直通話 data=conn.recv(1024) if not data: print('客戶端已經斷開') break print('接收的數據',data) print('開始執行程序') res=os.popen(data.decode()).read() print('before send',len(res)) if len(res)==0: res='沒有結果' file_size=len(res.encode()) print(file_size) conn.send(str(file_size).encode('utf-8')) conn.send((res.encode('utf-8'))) print('send done') server.close()socket

import socket import os client=socket.socket() client.connect(('127.0.0.1',6969)) while True: cmd=input('>>:') if len(cmd)==0: continue client.send(cmd.encode('utf-8')) total_size=client.recv(1024)#總的數據大小 print('總的大小:',total_size) received_size=0 while received_size<int(total_size.decode()): res=client.recv(1028)#設置爲1024是一直出錯,因此設置爲1028又正確啦 print(received_size) print(res.decode()) received_size +=len(res) else: print('zuizhongdaxiao',received_size) client.close()ui

注意:len('漢')的長度爲1 len(('漢').encode())的長度爲3code

相關文章
相關標籤/搜索