I was wondering how to handle forms that send files using a socket server in python.
This is what my server code currently looks like:
import socket # Import socket module
import time
s = socket.socket() # Create a socket object
port = 12345 # Reserve a port for your service.
s.bind(('', port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
data = c.recv(10240)
with open('filename{}.txt'.format(addr), 'wb') as f:
f.write(data)
print(time.ctime(), ': Got connection from', c, addr)
c.close()
I am using a form whose action
attribute points to localhost:12345
. I am sending text data as well as attaching an image. However, when I look at the txt file, I only see the headers. How do I get the image from this?
Or am I going about this in completely the wrong direction?
So this is my edited code:
while True:
c, addr = s.accept() # Establish connection with client.
print(time.ctime(), ': Got connection from', c, addr)
data = []
bytes_recd = 0
while 1:
chunk = c.recv(10240)
if chunk == b"" or len(chunk):
break
data.append(chunk)
bytes_recd = bytes_recd + len(chunk)
print(time.ctime(), bytes_recd)
data = b"".join(data)
print('reached here')
It stops printing the time, bytes_recd after everything has been received, but it never breaks the loop. Is there any reason why it does that?