简体   繁体   中英

Bidirectionnal communication Socket in Python

I am developing two scripts to send a file from a Client to a Server using Socket in Python. I can successfully send and receive the file from both Client Side and Server Side. Now, I would like the Server to send a confirmation that the whole file has been received (Send a simple string). But when, I try to receive from the Client side it seems to stop the program.

Here is my code to send the file and receive the status on the Client side :

zip_data_file = open(zip_file_name, 'rb')
data = zip_data_file.read()
while data:
    self.sock.send(data)
    data = zip_data_file.read()
print('File sent !')
zip_data_file.close()
state = str(self.sock.recv(1024).decode())

And here is the code for receiving/creating the file and send the status :

with open(new_file_name, 'wb') as file_created:
    data = connection.recv(1024)
    print('Receiving the file...')

    while data:
        file_created.write(data)
        data = connection.recv(1024)
print('Successfully got the file ', new_file_name)
connection.send("Done".encode())

Does anyone know where it could be from or how to solve this problem ? Thank you :)

while data: file_created.write(data) data = connection.recv(1024)

You assume that data will somehow be empty if the client is done sending. But the only concept of "done" built into TCP is to shutdown the connection. Without such a shutdown the server will not be aware that the client is finished but will instead expect the client to send more data.

One way to trigger such shutdown is to close the socket. Only this will close the whole connection and the client will not be able to receive any data from the server. Instead you can do a one-side shutdown with self.sock.shutdown(1) in which case the client will signal that it will not send any more data in the TCP connection but will still be able to receive data from the server:

self.sock.shutdown(1)
state = str(self.sock.recv(1024).decode())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM