Last active
October 26, 2022 06:10
-
-
Save DavesCodeMusings/71103111050ede309ad983d7e368ffbd to your computer and use it in GitHub Desktop.
Echo-back HTTP server to demonstrate MicroPython uasyncio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Example of using uasyncio to run a web server. | |
| # The server does nothing but echo back what was sent to it. | |
| # But the point here is to demonstrate the use of uasyncio, callbacks, | |
| # and the mixing of async and regular (synchronous) functions. | |
| import uasyncio | |
| # This is a synchronous function that gets called from inside the async function. | |
| def create_http_response(body): | |
| res_lines = [] | |
| res_lines.append('HTTP/1.1 200 OK') | |
| res_lines.append(f'Content-Length: {len(body)}') | |
| res_lines.append('Content-Type: text/plain') | |
| res_lines.append('Server: uasyncio (MicroPython)') | |
| res_lines.append('Connection: close') | |
| res_lines.append('') | |
| res_lines.append(f'{body}') | |
| return '\r\n'.join(res_lines) | |
| # This is the callback function that gets executed when there's a new connection. | |
| async def on_connect(reader, writer): | |
| print("Client connected.") | |
| req_buffer = await reader.read(1024) | |
| print("Input read.") | |
| print(req_buffer) | |
| body = req_buffer.decode('utf8') | |
| res = create_http_response(body) | |
| writer.write(res) | |
| print("Response sent.") | |
| await writer.drain() | |
| reader.close() | |
| await reader.wait_closed() | |
| writer.close() | |
| print("Connection closed.") | |
| # Here, the server is created and inserted into the event loop as a task. | |
| print("Server starting...") | |
| server = uasyncio.start_server(on_connect, '0.0.0.0', 80, 5) | |
| loop = uasyncio.get_event_loop() | |
| loop.create_task(server) | |
| loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment