预备知识:
关于http 协议的基础请参考这里。
关于socket 基础函数请参考这里。
关于python 网络编程基础请参考这里。
一、python socket 实现的简单http服务器
废话不多说,前面实现过使用linux c 或者python 充当客户端来获取http 响应,也利用muduo库实现过一个简易http服务器,现在来实现一个python版
的简易http服务器,代码改编自 http://www.cnblogs.com/vamei/ and http://www.liaoxuefeng.com/
httpServer.py
Python Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
|
#!/usr/bin/env python #coding=utf-8
import socket import re
HOST = '' PORT = 8000
#Read index.html, put into HTTP response data index_content = ''' HTTP/1.x 200 ok Content-Type: text/html
'''
file = open('index.html', 'r') index_content += file.read() file.close()
#Read reg.html, put into HTTP response data reg_content = ''' HTTP/1.x 200 ok Content-Type: text/html
'''
file = open('reg.html', 'r') reg_content += file.read() file.close()
#Read picture, put into HTTP response data file = open('T-mac.jpg', 'rb') pic_content = ''' HTTP/1.x 200 ok Content-Type: image/jpg
''' pic_content += file.read() file.close()
#Configure socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((HOST, PORT)) sock.listen(100)
#infinite loop while True: # maximum number of requests waiting conn, addr = sock.accept() request = conn.recv(1024) method = request.split(' ')[0] src = request.split(' ')[1]
print 'Connect by: ', addr print 'Request is:\n', request
#deal wiht GET method if method == 'GET': if src == '/index.html': content = index_content elif src == '/T-mac.jpg': content = pic_content elif src == '/reg.html': content = reg_content elif re.match('^/\?.*$', src): entry = src.split('?')[1] # main content of the request content = 'HTTP/1.x 200 ok\r\nContent-Type: text/html\r\n\r\n' content += entry content += '<br /><font color="green" size="7">register successs!</p>' else: continue
#deal with POST method elif method == 'POST': form = request.split('\r\n') entry = form[-1] # main content of the request content = 'HTTP/1.x 200 ok\r\nContent-Type: text/html\r\n\r\n' content += entry content += '<br /><font color="green" size="7">register successs!</p>' |