简单的http服务器

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()

 

发布了20 篇原创文章 · 获赞 4 · 访问量 7007
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 终极编程指南 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览