asyncio --- 异步 I/O http服务代码
import asyncio
async def service(reader,writer):
data = await reader.read(1024) #同步读取数据
data =data.decode().replace('\r','<br/>')
print(writer.get_extra_info('peername')) #获取连接信息
writer.write(b'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n') #返回HTTP响应头
#writer.write(b'hi fukun\r\n')
writer.write(data.encode()) #直接返回响应信息
writer.close()
#print(data)
async def server_run():
server = await asyncio.start_server(service,'127.0.0.1',8888)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever() #开始连接
asyncio.run(server_run())
在linux python3.8测试通过。
import uasyncio
import gc
async def service(reader,writer):
try:
data = await reader.read(1024)
print(data)
await writer.awrite('HTTP/1.1 200 ok\r\n\r\n hi fukun'.encode())
await writer.awrite(data)
except:
print("传输错误!")
finally:
await writer.aclose()
gc.collect()
def start():
loop = uasyncio.get_event_loop() //获取协议
#loop.call_soon(uasyncio.start_server(service, "0.0.0.0", 80))
loop.create_task(uasyncio.start_server(service, "0.0.0.0", 80))
loop.run_forever()
loop.close()
uasyncio.run(start())
通过micropython 实现