Thanks for that hint !
I implemented it, and for those small files I host it works.
I did ampy put a 229283 bytes file and request that via "
http://192.168.4.1/Peek_2022-07-07_02-56.gif" with wget.
Seldom I got the whole size, most times a little less.
That is because "cl.close()" seems not to wait until client has received all data.
I added "sleep_ms(100)", but that does not really help.
Commenting out "cl.close()" for letting garbage collection close the socket does not work at all.
So how can I "wait until all cl.send() data was received by client", before calling "cl.close()" ?
- mp.socket.close.better.png
- mp.socket.close.better.png (38.44 KiB) Viewed 2936 times
Current main.py:
Code: Select all
import rp2
import network
import machine
import socket
from time import sleep_ms
ap = network.WLAN(network.AP_IF)
ap.config(essid="pico_w_ap")
ap.active(True)
led = machine.Pin('LED', machine.Pin.OUT)
led.off()
# HTTP server with socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(10)
print('Listening on', addr)
# Listen for connections
while True:
try:
cl, addr = s.accept()
led.on()
# print('Client connected from', addr)
r = str(cl.recv(1024))
# print(r)
r = r[r.find("/"):]
r = r[1:r.find(" ")]
if (r == ""):
r = "index.html"
# print(r)
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
send_file_buffer_size = 1024
with open(r, 'rb') as file:
while True:
buf = file.read(send_file_buffer_size)
if len(buf):
cl.send(buf)
if len(buf) < send_file_buffer_size:
break;
sleep_ms(100)
cl.close()
led.off()
except OSError as e:
cl.close()
# print('Connection closed')
led.off()
Here are example wget calls demonstrating the different sizes received:
Peek_2022-07-07_02-56.gif
Code: Select all
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:31 (617 KB/s) - ‘Peek_2022-07-07_02-56.gif.8’ saved [227395]
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:33 (629 KB/s) - ‘Peek_2022-07-07_02-56.gif.9’ saved [227127]
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:36 (625 KB/s) - ‘Peek_2022-07-07_02-56.gif.10’ saved [229283]
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:41 (623 KB/s) - ‘Peek_2022-07-07_02-56.gif.11’ saved [229283]
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:47 (615 KB/s) - ‘Peek_2022-07-07_02-56.gif.13’ saved [229283]
$ wget http://192.168.4.1/Peek_2022-07-07_02-56.gif 2>&1 | grep saved
2022-07-07 10:05:49 (617 KB/s) - ‘Peek_2022-07-07_02-56.gif.14’ saved [228611]
$