zoukankan      html  css  js  c++  java
  • 【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, '
    '
         
        # 显示请求信息
        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:
    ', response
        c.close()
    






  • 相关阅读:
    显示器接口
    常用英语-持续更新
    Web Service
    单元测试--Moq
    单元测试--Xunit
    Asp.Net WebApi 跨域问题
    VS中常用的快捷键
    单元测试--最佳实践
    设计模式--建造者模式
    windows10搭建GitBucket服务器(1)
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5362987.html
Copyright © 2011-2022 走看看