Socket receives Big Data
The previous blog, that is, when the server sends the data to the client, which is larger than the data set by the client, the data remaining data sent by the data service will be present in the IO buffer, which will result in the integrity of the data we want to obtain.
Solution Ideas:
1, the large client to receive the size of the data, because the official recommendation can only receive 8k of data, the server sent over the data can easily be greater than 8K, this idea can not fundamentally solve the problem (not recommended)
2, the client can receive more than a few times, the server to the client before sending data, first calculate to send the client data size (len () to determine the length of the file), for example, to send the client data is 5k size, the first 5K this value sent to the client, the client knows that the total will receive 5K value, You know how many times you need to receive it and loop it until the 5k data is fully received.
Logical Flowchart:
Service-Side code:
Import Socket,os Server = Socket.socket () server.bind (("localhost", 9999)) Server.listen (5) while True: conn,addr = Server.accept () print ("New addr:", addr) while True: data = CONN.RECV (1024x768) if not data: print (" Client disconnected ") Break Print (" Execute command: ", data) cmd_res = Os.popen (Data.decode ()). Read () print (" Before Send: ", Len (cmd_res)) If Len (cmd_res) = = 0: cmd_res = "cmd has no output ..." conn.send (str (Len Cmd_res.encode ( )). Encode ()) #发送服务端发送给客户端数据的长度 conn.send (Cmd_res.encode ("Utf-8")) #发送服务端的数据 print ("Send Done ") Server.close ()
Client code:
Import Socket client = Socket.socket () client.connect (("localhost", 9999) while True: cmd = input (">>>:"). Strip () if len (cmd) = = 0:continue client.send (Cmd.encode ("Utf-8")) cmd_res_size = CLIENT.RECV (1024) #接收命令的长度 Print ("command result size:", Cmd_res_size.decode ()) recevied_size = 0 #接收客户端发来数据的计算器 Recevied_data = B ' #客户端每次发来内容的计数器 while recevied_size < int (Cmd_res_size.decode ()): #当接收的数据大小 less than The data sent by the client cmd_res = CLIENT.RECV (1024x768) recevied_size + = Len (cmd_res) #每次收到的服务端的数据有可能小于1024, so you must use Len to determine Recevied_data + = cmd_res else: print (Recevied_data.decode ("Utf-8", "ignore")) print ("cmd res Receive done ..... ", Recevied_size) Client.close ()
"Python"--socket receives big data