Sending a file over TCP sockets in Python

后端 未结 6 1219
太阳男子
太阳男子 2020-12-02 08:14

I\'ve successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I\'m facing issues. The server loop is not e

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 08:57

    You can send some flag to stop while loop in server

    for example

    Server side:

    import socket
    s = socket.socket()
    s.bind(("localhost", 5000))
    s.listen(1)
    c,a = s.accept()
    filetodown = open("img.png", "wb")
    while True:
       print("Receiving....")
       data = c.recv(1024)
       if data == b"DONE":
               print("Done Receiving.")
               break
       filetodown.write(data)
    filetodown.close()
    c.send("Thank you for connecting.")
    c.shutdown(2)
    c.close()
    s.close()
    #Done :)
    

    Client side:

    import socket
    s = socket.socket()
    s.connect(("localhost", 5000))
    filetosend = open("img.png", "rb")
    data = filetosend.read(1024)
    while data:
        print("Sending...")
        s.send(data)
        data = filetosend.read(1024)
    filetosend.close()
    s.send(b"DONE")
    print("Done Sending.")
    print(s.recv(1024))
    s.shutdown(2)
    s.close()
    #Done :)
    

提交回复
热议问题