# 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。
