Commit ed5153df authored by Klint Youngmeyer's avatar Klint Youngmeyer
Browse files

Add basic webserver example. Only works with for small files at this point. Still a WIP

parent 83cc1980
import pyb
import network
import socket
# nic = network.RS911X(pyb.SPI(2), pyb.Pin("I0"), pyb.Pin("E3"), pyb.Pin("E4"))
# nic.connect('ASUS_E8_2G', '3197597781')
def webserver(nic):
allowed_errors = [105]
HOST, PORT = nic.ifconfig()[0], 8082
print("Simple Webserver Running at: {}:{}".format(HOST, PORT))
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((HOST, PORT))
my_socket.listen(1)
while True:
attempts = 0
connection = None
address = None
while attempts < 3:
try:
connection, address = my_socket.accept()
break
except OSError as e:
attempts += 1
if e.args[0] not in allowed_errors:
print("OS Error: {}".format(e))
pyb.delay(10)
request = connection.recv(1024).decode('utf-8')
string_list = request.split(' ')
method = string_list[0]
requesting_file = string_list[1]
try:
myfile, data = requesting_file.split('?')
except ValueError:
myfile = requesting_file.split('?')[0]
data = None
myfile = myfile.lstrip('/')
if(myfile == '/'):
myfile = 'index.html'
try:
file = open(myfile, 'rb')
response = file.read()
file.close()
header = 'HTTP/1.1 200 OK\n'
if(myfile.endswith(".jpg")):
mimetype = 'image/jpg'
elif(myfile.endswith(".css")):
mimetype = 'text/css'
else:
mimetype = 'text/html'
header += 'Content-Type: '+str(mimetype)+'\n\n'
except Exception:
header = 'HTTP/1.1 404 Not Found\n\n'
response = '<html><body><center><h3>Error 404: File not found</h3><p>Python HTTP Server</p></center></body></html>'.encode('utf-8')
final_response = header.encode('utf-8')
final_response += response
connection.send(final_response)
#connection.close()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment