我们写出一个HTTP服务器端:
Wow, Python Server#coding;utf-8
import socket# Address
HOST = ''
PORT = 8000# Prepare HTTP response
text_content = '''HTTP/1.x 200 OK
Content-Type: text/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()
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 waitings.listen(3)conn, addr = s.accept()request = conn.recv(1024)method = request.split(' ')[0]src = request.split(' ')[1]# deal with GET methodif method == 'GET':# ULRif src == '/test.jpg':content = pic_contentelse: content = text_contentprint 'Connected by', addrprint 'Request is:', requestconn.sendall(content)# close connection
如我们上面所看到的,服务器会根据request向客户传输的两条信息text_content和pic_content中的一条,作为response文本。整个response分为起始行(start line), 头信息(head)和主体(body)三部分。起始行就是第一行:
1 | HTTP/1.x 200 OK |
它实际上又由空格分为三个片段,HTTP/1.x表示所使用的HTTP版本,200表示状态(status code),200是HTTP协议规定的,表示服务器正常接收并处理请求,OK是供人来阅读的status code。