简体   繁体   中英

send and receive a file in python sockets

This has for the most part been answered here I have been trying to modify the server (to send) and client (to receive) feedback from the server upon receipt of the entire file.

below is the client server code; as it is presently both client and server hang. ie. indefintely go into "busy" state (both client and server do nothing, until ctrl-c on the server reports failure here "l = sc.recv(1024)" and ctrl-c on the client reports failure here "reply =s.recv(1024)")

import socket
import sys
s = socket.socket()
s.bind(("localhost",3000))
s.listen(10)
i=1
while True:
    sc, address = s.accept()
    print address
    f = open('tranmit.jpg",'wb') #open in binary
    l = 1
    while(l):
        l = sc.recv(1024)
        while (l):
            f.write(l)
            l = sc.recv(1024)
        f.close()
        sc.send("received") # Would like to send back a response

    sc.close()

s.close()
------------------------------------------------------------
#client
s = socket.socket()
s.connect(("localhost",3000))
f=open ("tranmit.jpg", "rb") 
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
reply =s.recv(1024) # Feedback: would like the receive feedback from the server.
print reply
s.close()

The code works fine without the feedback lines added in (as in the link above), does anyone have an idea on how to keep this working with the feedback as well? Thanks.

Your client must indicate, somehow, that the entire file has been sent. As it stands, your server has no way of knowing when the client's send operations are complete.

One solution is to call socket.shutdown after all transmissions are complete. Here is a new version of your client program. No changers were required to your server program.

#client
import socket
s = socket.socket()
s.connect(("localhost",3000))
f=open ("tranmit.jpg", "rb")
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
s.shutdown(socket.SHUT_WR)
reply =s.recv(1024) # Feedback: would like the receive feedback from the server.
print reply
s.close()

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