Skip to main content
 首页 » 编程设计

python之在 Python 中的 sock.sendall() 之后调用 sock.recv()

2025年05月04日14lautakyan007

我提供了一个工作客户端和服务器文件。 客户端向服务器发送图片。 当你注释掉时:

data = sock.recv(1024) 
print("received: ",str(data,"UTF-8")) 

图片不会再上传到服务器了... (收到服务器的上传消息后,我想在以后再上传一张图片。)

那么为什么在 sock.sendall() 之后调用 sock.recv() 会打乱通信? (我该如何解决)

客户端.py:

import socket 
PICLOC = "/home/wr/Documents/Data/cola_big_1.jpg" 
HOST = 'localhost' 
PORT = 9995 
 
# Create a socket (SOCK_STREAM means a TCP socket) 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
 
try: 
 
   # Connect to server and send data 
   sock.connect((HOST, PORT)) 
 
   # Send a command to the server 
   command = "pictureRequest" 
   data = sock.send(bytes(command, "utf-8")) 
 
   pictures = [] 
   pictures.append(PICLOC) 
 
   data = sock.recv(1024) 
   print("received : ",data.decode()) 
 
   for picture in pictures: 
       # sending a picture to the server 
       f = open(picture,'rb').read() 
       numBytes = len(f) 
       x = str(numBytes) 
       print("numBytesToSend: ",x) 
       data = sock.sendall(f) 
       ''' 
       data = sock.recv(1024) 
       print("received: ",str(data,"UTF-8")) 
       ''' 
finally: 
   sock.close() 

服务器.py

import socketserver 
 
HOST = "localhost" 
PORT =  9995 
 
TARGETPICLOC = "/home/wr/Documents/Data/Received/cola_big_1.jpg" 
 
class MyTCPHandler(socketserver.BaseRequestHandler): 
 
 
  def findProduct(self): 
    """ 
        Method called to find the product 
    """ 
 
    # Receiving command from the client 
    msg = "ok to send"  
    data = self.request.sendall(bytes(msg,"utf-8")) 
    print("send msg") 
 
    # TODO 6 pictures in array ! 
    # Sending a picture from client to server   
    pictures = [] 
    pictures.append(TARGETPICLOC) 
 
 
    for picture in pictures: 
        total_data=[] 
 
        # open the target picture-file  
        newFile = open(picture,'wb') 
 
        data = self.request.recv(1024) 
        newFile.write(data) 
        total_data.append(data) 
        while len(data)>0 : 
            data = self.request.recv(1024) 
            newFile.write(data) 
            total_data.append(data) 
 
        data = b''.join(total_data) 
        print("#bytes : ",len(data)) 
        newFile.close() 
 
        msg = "picture uploaded" 
        data = self.request.sendall(bytes(msg,"utf-8")) 
        print("msg send ") 
 
 
  def handle(self): 
 
    # Receiving command from the client 
    data = self.request.recv(1024) 
    command = str(data,"utf-8") 
    print("command: ",command) 
 
    if command=="pictureRequest" : 
        self.findProduct() 
 
    print("Request ended !!") 
 
 
 
if __name__ == "__main__": 
   HOST, PORT = HOST,PORT 
   server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) 
   server.serve_forever() 

谢谢你看这个问题

请您参考如下方法:

So why is calling sock.recv() after sock.sendall() messing up the communication ?

那是因为这个sock.recv()调用的客户端在等待来自服务器的数据(你打算从服务器接收图片上传消息),但是服务器卡在了循环中

        while len(data)>0 : 
            data = self.request.recv(1024) 

因为 recv() 仍在等待来自客户端的数据并阻塞。如果省略 sock.recv() 调用,客户端将进入 sock.close();只有此后 self.request.recv(1024) 返回零长度数据,以便服务器可以感知传输结束并跳出 while 循环。

( and how should I solve it )

您可以在发送图片之前将要发送的字节数 (x = str(numBytes)) 发送到服务器,这样服务器就可以在 的长度时循环total_data小于这个数。