Receiving numerous data with Python socket

Asked

Viewed 217 times

0

I’m having a problem with my script, I have a server.py and a client py. and my problem is to receive and send large amounts of bytes.

I want to transfer large amounts of bytes of files to the client and also to the server, only I have a limitation on recv(1024). It will receive 1024 bytes and if I have a quantity x of bytes to send or receive, how can I create this ?

Well I would create a function of my own to deal with this problem:

def recvall():
    pass

The problem is that I am not able to develop a logic to solve this problem to receive so many bytes.

The logic of my script is, when the client sends an X command to the server, it sends the file to the client, if the client sends a Y command to the server, the client has to send the file to the server.

#server.py
decode = lambda data: data.decode('utf-8')

def Socket():
    global s
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def accept(port):
    Socket()
    host = ''#socket.gethostbyname(socket.gethostname())
    s.bind((host, port))
    s.listen(1)
    conn, addr = s.accept()
    while True:
        data = decode(conn.recv(1024))
        if data == 'enviarfile':
            with open('doc.pdf', 'rb') as f
                pass

# client.py
def client(port):
    host= '0.0.0.0'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((host, port))
except Exception as err:
    print(err)
    sys.exit()

print('CONNECTED\n')

while True:
    command = input('comando:')
    s.send(command.encode('utf-8'))
    if command == 'enviarfile':
        with open('doc.pdf', 'wb') as f
             pass

    if 'exit' in command:
        break
    print(s.recv(1024).decode('utf-8')+'\n')

That function I would create def recvall() not only for files but also for messages. The client sends 'oi' and print on the server screen and the server would send a reply that received the client’s message.

  • The limit on recv causes every call of the method to get only 1024 bytes, but this does not mean that you would lose the rest of the bytes that were sent in the send. That being said, you just need to upload all the bytes of the file and get the content with the recv little by little through a repeat block.

  • thanks friend.

1 answer

0


Its implementation of recvall() has to call recv(1024) within a loop and accumulate the received buffers. When recv() returns zero, it is because the other side closed the connection and the transmission ended.

Another problem is that you are sending interactive commands, in addition to files, then you will have to create a protocol, to detect inside the received buffer where the command ends and starts the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.