用python3写一个简单的http服务器

# Written by Vamei

import socket

# Address
HOST = ''
PORT = 8000

# Prepare HTTP response
text_content = '''HTTP/1.x 200 OK  
Content-Type: text/html

<head>
<title>WOW</title>
</head>
<html>
<p>Wow, Python Server</p>
<IMG src="test.jpg"/>
</html>
'''

# Read picture, put into HTTP format
f = open('test.jpg','rb')
pic_content = '''
HTTP/1.x 200 OK  
Content-Type: image/jpg

'''
# pic_content = pic_content + f.read()
pic_content = pic_content.encode('UTF-8') + f.read()

f.close()

# Configure socket
s    = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))

# infinite loop, server forever
while True:
    # 3: maximum number of requests waiting
    s.listen(3)
    conn, addr = s.accept()
    request    = conn.recv(1024).decode()
    method    = request.split(' ')[0]
    src            = request.split(' ')[1]

    # deal with GET method
    if method == 'GET':
        # ULR    
        if src == '/test.jpg':
            content = pic_content
        else: content = text_content.encode()

        print ('Connected by', addr)
        print ('Request is:', request)
        conn.sendall(content)
    # close connection
    conn.close()

  初始代码来自http://www.cnblogs.com/vamei/archive/2012/10/30/2744955.html

  原始代码估计是在python2中运行的,在python3中运行报错,大部分报错由于类型转换导致的,大致的意思是说bytes类型不能与str类型直接相加,所以我们需要在关键处添加.encode()和.decode(),其他主要内容均来自vamei,实测可用。

  整个请求的流程,是客户端访问127.0.0.1:8000,服务器响应连接后,根据解析的method为‘GET’,发送给客户端准备好的text_content,发送完之后连接断开,客户端浏览器按照html的方式解析这段字符串内容,发现有一个链接指向根文件目录下的test.jpg,于是再次向服务端请求/test.jpg的内容,服务端同上,知道method为/test.jpg后,将准备好的图片内容加上文件头发送过去,发完连接立刻中断。

  所以HTTP其实是TCP的一种变种,先是建立一个长连接,然后一个客户端请求数据,服务端根据对方的请求发送相应数据,发完立刻断。而文中socket.SOCK_STREAM属性,其实就是指的TCP。

原文地址:https://www.cnblogs.com/wuzhenyang/p/6602733.html