python网络学习(02)
我们写出一个HTTP服务器端:
#coding;utf-8 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() 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) 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 print 'Connected by', addr print 'Request is:', request conn.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。