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

时间:2015-02-28 11:14:42

标签: python sockets python-3.x socketserver

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

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

图片将不再上传到服务器了... (从服务器收到上传消息后,我希望将来再上传另一张图片。)

那么为什么在sock.sendall()搞乱通信后调用sock.recv()? (以及我该如何解决它)

Client.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()

Server.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()

感谢您查看此问题

0 个答案:

没有答案