【Python】 做一个简单的 http server

# coding=utf-8
'''
Created on 2014年6月15日

@author: Yang
'''

import socket
import datetime
# 初始化socket
s = socket.socket()
# 获取主机名, 也能够使用localhost
# host = socket.gethostname()
host = "localhost"
# 默认的http协议端口号
port = 80
 
# 绑定serversocket的ip和端口号
s.bind((host, port))
 
# server名字/版本
server_name = "MyServerDemo/0.1"
 
# 缓存时间, 缓存一天
expires = datetime.timedelta(days=1)
# GMT时间格式
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
# 对应网页的内容
content = '''
<html>
<head><title>MyServerDemo/0.1</title></head>
<body>
<h1>coming soon</h1>
</body>
</html>
'''
 
# 可同一时候连接五个client
s.listen(5)
 
# server循环
while True:
    # 等待client连接
    c, addr = s.accept()
    print 'Got connection ', addr, '\n'
     
    # 显示请求信息
    print '--Request Header:'
    # 接收浏览器的请求, 不作处理
    data = c.recv(1024)
    print data
     
    # 获得请求的时间
    now = datetime.datetime.utcnow()
 
    # 对应头文件和内容
    response = '''HTTP/1.1 200 OK
Server: %s
Date: %s
Expires: %s
Content-Type: text/html;charset=utf8
Content-Length: %s
Connection: keep-alive
 
%s''' % (
server_name,
now.strftime(GMT_FORMAT),
(now + expires).strftime(GMT_FORMAT),
len(content),
content
)

    # 发送回应
    c.send(response)
    print '--Response:\r\n', response
    c.close()






posted @ 2016-04-07 12:22  lcchuguo  阅读(688)  评论(0编辑  收藏  举报