Python实现HTTP服务器

Python实现简单HTTP服务器


import socket

response  = b'HTTP/1.0 200 OK\r\n\r\nHello, world!'

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 80))
server.listen(20)

try:
	while True:
		client, address = server.accept()
		request = b''
		while b'\r\n\r\n' not in request:
			request += client.recv(1024)
			if len(request) > 4000:
				break
		print('-'*40 + '\n' + request.decode()[:-2])
		client.send(response)
		client.close()
finally:
	server.close()

带守护进程:


import os, sys, SocketServer

def daemon():
    if os.fork() != 0:
        sys.exit(0)
    os.setsid()
    if os.fork() != 0:
        sys.exit(0)
    os.chdir('/tmp')
    os.umask(0)

class TCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        self.data = self.request.recv(1024)
        respone = b'HTTP/1.1 200 OK\r\n\r\nOK'
        self.request.send(respone)

if __name__ == "__main__":
    daemon()
    SocketServer.ThreadingTCPServer.allow_reuse_address = True
    server = SocketServer.ThreadingTCPServer(('0.0.0.0', 8000), TCPHandler)
    try:
        server.serve_forever()
    except:
        pass
    server.server_close()