file truncated in http server

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

file truncated in http server

Post by devnull » Fri Feb 17, 2017 11:59 am

Hi;

I am facing a problem whereby a file that is read is truncated while sending over a socket.

It is a simple web server that replies with a file that is stored on the flash file system, it always gets truncated at 1,072 bytes/chars.

If I print the file to the console instead, the entire file gets printed, but it refuses to send the whole file over the socket.

The full file size is 2,211 characters / bytes so this is not a huge file:

here's the method that gets are returns the file, not sure if it is sufficient ?

Code: Select all

def page(cl):
	with open('/www/js/index.js', 'r') as html:
		cl.send(html.read())
	cl.close()
	
while True:
    try:
        cl, addr = s.accept()
        print('client connected from', addr)
        raw = cl.recv(1024).decode('UTF-8')
        if not raw:
            print('Null Request.',addr)
            cl.close()
        else:
            print(raw)
            page(cl)        
        
    except Exception as err:
        print(err)

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: file truncated in http server

Post by devnull » Fri Feb 17, 2017 12:09 pm

OK, my apologies, after several hours, I have just solved it.

I thought that sendall() was just an alias for send() but it is not, and the solution was to use sendall() instead.

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: file truncated in http server

Post by Roberthh » Fri Feb 17, 2017 12:21 pm

Again: did you try:

Code: Select all

cl.sendall(html.read())
instead of just cl.send()? While read() is defined to read the whole file, send() does not promise to supply all data provided. It will return the number of bytes actually sent.

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: file truncated in http server

Post by devnull » Fri Feb 17, 2017 12:31 pm

Thanks so much for helping, but I think we must have posted at the same time.

Previously I was using sockets on esp32 and in that implementation send() is an alias for sendall() and so when I ported it over to esp8266 it was behaving as described.

But as you suggested, changing to sendall() solved the problem, thanks again

Post Reply