当前位置:首页 > 技术 > Python > 正文内容

python编写的简单http请求和应答

watrt4年前 (2019-12-31)Python12740

响应(服务端)

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上面使用的。

分享给朋友:

相关文章

micropython中使用rtc设置时间

micropython中使用rtc设置时间

micropython中使用rtc设置时间from machine import RTC rtc = RTC() rtc.datetime((2017, 8, 23, 1, 12, 48, 0, 0)) # set a specific date and time print(rtc.datetime(...

micropython 使用oled显示前面设置的时间。

micropython 使用oled显示前面设置的时间。

from machine import I2C, Pin import ssd1306,time    #这里引用的是官方的ssd1306库。可以在github上下载下来放入库中。 i2c = I2C(-1, Pin(14), Pin(2)) display = ssd1306.SSD1306_I2C(128, 64, i...

python利用pyinstaller打包简明教程

python利用pyinstaller打包简明教程

在创建了独立应用(自包含该应用的依赖包)之后,还可以使用 PyInstaller 将 Python 程序生成可直接运行的程序,这个程序就可以被分发到对应的 Windows 或 Mac OS X 平台上运行。安装 PyInstallePython 默认并不包含 PyInstaller 模块,因此需要自行安装 PyInstaller 模块。安装 PyInstaller 模块与安装其他 Python 模块一样,使用 pip 命令安装即可。在命令行输入如下命令:pip install ...

Python使用struct处理二进制(pack和unpack用法)

Python使用struct处理二进制(pack和unpack用法)

有的时候需要用python处理二进制数据,比如,存取文件,socket操作时.这时候,可以使用python的struct模块来完成.可以用 struct来处理c语言中的结构体. struct模块中最重要的三个函数是pack(), unpack(), calcsize()pack(fmt, v1, v2, ...)     按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流) un...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。