美文网首页
micropython-http

micropython-http

作者: yichen_china | 来源:发表于2024-05-18 17:35 被阅读0次
    import usocket as socket
    import html.index  as html
    def getHtml():
        return html.index()
    def httpServer(ip,port):
        # 创建socket对象,设置为TCP类型
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定到本地IP地址和80端口
        print('Listening on http://',ip,":", port)
        s.bind((ip, port))
        # 开始监听连接请求,最大队列长度为5
        s.listen(5)
        return s
    def listenHttp(s):
        # 接受一个客户端的连接请求,返回一个新的socket对象和客户端地址
        conn, addr = s.accept()
        # 打印客户端地址
        print('Got a connection from %s' % str(addr))
        # 接收客户端发送的数据,最多接收1024字节
        request = conn.recv(1024)
        # 打印客户端发送的数据
        print('Content = %s' % str(request))
        # 向客户端发送HTTP响应头和HTML页面内容
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(getHtml())
        # 关闭连接
        conn.close()
    

    html/Index.py

    class Index:
        def __init__(self):
            pass
        def index(self):
                # 定义一个HTML页面的内容,用于返回给客户端
            return  """<!DOCTYPE html>
            <html lang="zh-CN" manifest="IGNORE.manifest">
                <head>
                    <meta charset="utf-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <meta name="viewport"
                        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
                    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
                    <meta http-equiv="Pragma" content="no-cache" />
                    <meta http-equiv="Expires" content="0" />
                    <title>首页</title> 
                </head>
                <style>
                    .form-item {
                        text-align: center;
                        line-height: 2em;
                    }
    
                    .form-item[type=button] {
                        line-height: 2em;
                    }
                    input{
                        line-height: 2em;
                    }
                    button {
                        padding: 5px;
                        width: 100%;
                        background-color: green;
                        color: white;
                        border: none;
                    }
    
                    button:hover {
                        background-color: green;
                    }
    
                    button:active {
                        background-color: #888;
                    }
    
                    button:disabled {
                        background-color: gray;
                        color: black;
                    }
                    form{
                        padding: 10px;
                        background-color: aliceblue;
                    }
                </style>
                <body>
                    <div style="display: flex;justify-content: center;width: 100vw;">
                        <form action="">
                            <div class="form-item" style="text-align: center;">
                                WIFI配置
                            </div>
                            <div class="form-item">
                                名称: <input type="text" name="firstname"><br>
                            </div>
                            <div class="form-item">
                                密码: <input type="text" name="lastname">
                            </div>
                            <div class="form-item">
                                <button type="button" value="确认">确认</button>
                            </div>
                            <div  class="form-item">
                                当前状态
                            </div>
                        </form>
                    </div>
                </body>
            </html>
            """
    
    
    

    WebService.py

    import socket, time, re
    #import socket
    from html.Index import Index
    class WebService:
        def __init__(self,IP="0.0.0.0",PORT=80,):
            self.IP = IP
            self.PORT = PORT
            self.CLIENT = None
            print("启动web服务器2")
        def run(self):
            webserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    #创建套接字
            webserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  #设置给定套接字选项的值
            #webserver.settimeout(2000)
            #ip="192.168.4.1" #AP's IP
    #         a=1
            webserver.bind((self.IP, self.PORT))                                       #绑定IP地址和端口号
            webserver.listen(5)                                              #监听套接字
            self.webserver=webserver
            print("web:",self.IP,":",self.PORT)
    #         print(self.PORT)
            while True:
                conn, addr = webserver.accept()                                #接受一个连接,conn是一个新的socket对象
                self.CLIENT = conn
                self.ADDR =addr
                request = conn.recv(1024)                              #从套接字接收1024字节的数据
                 # 打印客户端发送的数据
                print('Content = %s' % str(request))
                if len(request)>0:
                    request = request.decode()
                    result = re.search("(.*?) (.*?) HTTP/1.1", request)
                    if result:
                        method = result.group(1)
                        url = result.group(2)
                        print(url)
                        payload = {}#将post数据存数组
                        if method == "POST":#获得post数据
                            print("POST")
                            postdata = re.search(".*?\r\n\r\n(.*)", request).group(1)
                            if postdata:
                                lists = postdata.split("&")
                                for list in lists:
                                    k,v = list.split("=")
                                    payload[k]=v
                          #print(payload)
    
                                #conn.sendall("HTTP/1.1 200 OK\nConnection: close\nServer: Esp8266\nContent-Type: text/html;charset=UTF-8\n\n")
    #                             conn.send("HTTP/1.1 200 OK\r\n")
    #                             conn.send("Server: Esp8266\r\n")
    #                             conn.send("Content-Type: text/html;charset=UTF-8\r\n")
    #                             conn.send("Connection: close\r\n")
    #                             conn.send("\r\n")
                        if method == "GET":#获得get数据
                            print("GET")
                        conn.send('HTTP/1.1 200 OK\n')
                        conn.send('Content-Type: text/html\n')
                        conn.send('Connection: close\n\n')
                        print(url)
                        if url == "/":
                            print("url:/")
                            conn.sendall(Index().login())
                        elif url == "/login":
                            print("url:/login")
                            conn.sendall(Index().login())
    #                         conn.send("\r\n")  # 发送结束
                        else:
                            print("not found url")
                    else:
                        print("no request")
                        conn.close()
                        print("out %s" % str(addr))
    #   测试方法 返回文档内容   httpServer(self,ip,port).listenHttp()
        def getHtml(self):
            Index().login();
    #   简单实现web 服务
        def httpServer(self,ip,port):
            # 创建socket对象,设置为TCP类型
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # 绑定到本地IP地址和80端口
            print('Listening on http://',ip,":", port)
            s.bind((ip, port))
            # 开始监听连接请求,最大队列长度为5
            s.listen(5)
            self.s=s
            return self
    #   简单实现web端口监听
        def listenHttp(self):
            s=self.s
            # 接受一个客户端的连接请求,返回一个新的socket对象和客户端地址
            conn, addr = s.accept()
            # 打印客户端地址
            print('Got a connection from %s' % str(addr))
            # 接收客户端发送的数据,最多接收1024字节
            request = conn.recv(1024)
            # 打印客户端发送的数据
            print('Content = %s' % str(request))
            # 向客户端发送HTTP响应头和HTML页面内容
            conn.send('HTTP/1.1 200 OK\n')
            conn.send('Content-Type: text/html\n')
            conn.send('Connection: close\n\n')
            conn.sendall(self.getHtml())
            # 关闭连接
    
    
    

    相关文章

      网友评论

          本文标题:micropython-http

          本文链接:https://www.haomeiwen.com/subject/gbrpxjtx.html