简单的http服务器

隐身守侯 提交于 2020-01-19 03:51:54
import socket
import re
compile=re.compile('GET (.+) HTTP/1.1\\r')
def getinfo():
    text=''
    with open(r'html路径','r') as f:
        a=f.readlines()
        for i in a:
            text=text+str(i)
    return text

def getinfo2():

    with open(r'图片路径','rb') as f:
        a=f.read()

    return a
print(getinfo())
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('10.6.3.140',800))
    print('listening....')
    sock.listen(5)
    while True:
        conn,addr = sock.accept()
        data = conn.recv(1024)
        recvstring=data.decode('utf-8')
        print(recvstring)
        refer=compile.findall(recvstring)
        print(refer)
        if refer!=[]:
            if refer[0]=='/test':
                print('123')
                conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=utf-8\r\n\r\n")
                conn.send("测试页面".encode("utf-8"))
            elif refer[0]=='/img':
                responseHeaders = "HTTP/1.1 200 OK\r\n\r\n"
                conn.send(responseHeaders.encode('utf-8'))
                conn.send(getinfo2())
            else:
                conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=utf-8\r\n\r\n")
                print(getinfo())
                conn.send(getinfo().encode('utf-8'))
        else:
            pass
        conn.close()


if __name__ =="__main__":
    main()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!