-3

I have looked every where on the net on how to send a file in python, 100% is a fail, no one can help. Are there any programmers out there that can help me send a file from client to server or the other way?

I can send txt very easy

#!/usr/bin/python
"""
Socket Client
"""
import socket #networking library
indent = ""
server = input("server name (default is " + socket.gethostname() + "): ") or socket.gethostname()

print("connecting to server at: %s" % server)

while True:
    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    clientSocket.connect((server, 23000)) 



    str = input("text to send: ")

    clientSocket.send(str.encode("utf-8")) #send text as encoded bytes

    print("received: %s" % clientSocket.recv(100).decode("utf-8")) 

    clientSocket.close()

    #strRecv = clientSocket.recv(500).decode("utf-8") #receive up to 500 bytes and decode into text
    #print(strRecv)
3
  • I would like the client side and server side so I can send a file. I would like to open a file. Break it down to pieces in a loop. Send each piece an compile it. Isn't that how it works, well that's why I am here. If I knew how to do it I wouldn't be here Commented Oct 20, 2014 at 11:50
  • So you just don't know how to open and read a file? Commented Oct 20, 2014 at 13:12
  • I am building an assignment for my Tafe class, thank you for you rhelp, I can work out the rest.. Thanks Matthias aswell Commented Oct 24, 2014 at 9:33

1 Answer 1

5

Very basic example:

Server to receive a file:

import socket
with socket.socket() as s:
    s.bind(('',8000))
    s.listen(1)
    with s.accept()[0] as c:
        chunks = []
        while True:
            chunk = c.recv(4096)
            if not chunk: break
            chunks.append(chunk)
    with open('out.txt','wb') as f:
        f.write(b''.join(chunks))

Client to send a file:

import socket
with socket.socket() as s:
    s.connect(('localhost',8000))
    with open('myfile.txt','rb') as f:
        s.sendall(f.read())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.