I am working on a web server to serve up a index.html file. I have it working fine using Python 3.6.3.
Here is that code that works just fine.
from http.server import BaseHTTPRequestHandler class GetHandler(BaseHTTPRequestHandler): def do_GET(self): try: f = open(‘index.html’,‘rb’) self.send_response(200) self.send_header(‘Content-type’, ‘text/html’) self.end_headers() self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404, ‘File Not Found: %s’ % self.path) if name == ‘main’: from http.server import HTTPServer server = HTTPServer((‘localhost’, 8080), GetHandler) print(‘Starting server, use to stop’) server.serve_forever()
Since Zerynth does not have wfile.write I don’t know what to use in its place.
I have tried,
f = open(“resource://index.html”,‘rb’)
data = f.read()
But when I open the browser, I only get the first character in the index.html file.
What can I use to send the whole file back to the browser ?
Here is the heart of the code which was taken from the Mini Web Server example
while True: try: # Type in your browser the board ip! print("Waiting for connection...") # here we wait for a connection clientsock,addr = sock.accept() print("Incoming connection from",addr) # yes! a connection is ready to use # first let's create a SocketStream # it's like a serial stream, but with a socket underneath. # This way we can read and print to the socket client = streams.SocketStream(clientsock) # let's read all the HTTP headers from the browser # stop when a blank line is received line = client.readline() while line!="\n" and line!="\r\n": line = client.readline() print("HTTP request received!") # let's now send our headers (very minimal) # hint: \n is added by print print("HTTP/1.1 200 OK\r",stream=client) print("Content-Type: text/html\r",stream=client) print("Connection: close\r\n\r",stream=client) # see? as easy as print! print("Hello Zerynth!",random(0,100),"",stream=client) # close connection and go waiting for another one client.close() except Exception as e: print("ooops, something wrong:",e)