web框架的本质(使用socket实现的最基础的web框架、使用wsgiref实现的web框架)

import socket

def handle_request(client):
    data = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("<h1>Hello word</h1>")

def main():
    sockobj = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sockobj.bind(('localhost',8888))
    sockobj.listen(5)

    while True:
        con1,address = sockobj.accept()
        handle_request(con1)
        con1.close()

if __name__ == "__main__":
    main()

  

#coding=utf-8
from wsgiref.simple_server import  make_server

def Runserver(data,start_response):
    #data里面包含的是客户发来的所有数据
    #start_response 封装了要返回给用户的数据(响应头、状态等)
    print data
    start_response('200 OK',[("Content-Type","text/html")])
    #返回的内容
    return  '<h1>Hello word </h1>'

if __name__ == "__main__":
    httpobj = make_server('',8888, Runserver)
    print 'port HTTP on port 8888'
    httpobj.serve_forever()

  

 

posted @ 2018-04-28 01:25  梦中琴歌  阅读(228)  评论(0编辑  收藏  举报