python编写的简单http请求和应答
响应(服务端)
import machine
import socket
pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)]
adc = machine.ADC(0)
html = """<!DOCTYPE html>
<html>
<head> <title>ESP8266 Pins</title> </head>
<body> <h1>ESP8266 Pins</h1>
<table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s
<tr><td>ad0</td><td>%d</td></tr>
</table>
</body>
<script type="text/javascript">
setTimeout(function(){ //使用 setTimeout()方法设定定时2000毫秒
window.location.reload();//页面刷新
},1000);
</script>
</html>
"""
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(3)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
response = html % ('\n'.join(rows),adc.read())
cl.send(response)
cl.close()请求(客户端)
try:
import usocket as socket
except:
import socket
def main(use_stream=False):
s = socket.socket()
ai = socket.getaddrinfo("028sd.net", 80)
print("Address infos:", ai)
addr = ai[0][-1]
print("Connect address:", addr)
request_url = 'GET / HTTP/1.1\r\nHost: 028sd.net\r\nConnection: close\r\n\r\n'
s.connect(addr)
if use_stream:
s = s.makefile("rwb", 0)
s.write(request_url.encode())
print(s.read(2048))
else:
s.send(request_url.encode())
print(s.recv(2048).decode('gbk'))
s.close()
main()代码是用于micropython上面使用的。


支付宝打赏
微信打赏 
