The first thing to say is that this is an impossible task, at least not a blog post can do. Avoid wasting time looking at the headlines and expecting the same fellow.
The main is to take Apache as the blueprint, through the Python script step-by-step to achieve the core functions of Apache. Learn about Python network programming and all aspects related to Web service energy.
Gossip less, directly on the code!
Import socket
Server=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Server.bind ((', 1234))
Server.listen (5)
While True:
Client,addr=server.accept ()
DATA=CLIENT.RECV (1024)
Client.send ("My WebServer")
Client.close ()
Test this server with the AB command:
ab-n500-c500 http://127.0.0.1:1234/
The test results are as follows:
By printing data, you get the information that the client agent submits to webserver.
get/http/1.1
user-agent:curl/7.12.1 (I686-REDHAT-LINUX-GNU) libcurl/7.12.1 openssl/0.9.7a zlib/1.2.1.2 libidn/0.5.6
host:127.0.0.1:1234
Pragma:no-cache
Accept: */*
We only care about the contents of the GET request here, and then return it to the client after the user's getting request is parsed to obtain the contents of the file in the specified directory.
Import socket
Import re
documentroot= "/root/"
Server=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Server.bind ((', 1235))
Server.listen (5)
While True:
Client,addr=server.accept ()
DATA=CLIENT.RECV (1024)
M=re.match (' Get/(. *) ', data) #由于ab使用的是http1.0 so it's different from the previous example.
Try: #为应对在进行ab测试时候可能的异常
Index=documentroot+m.group (1)
Html=open (Index, "R")
Client.send (Html.read ())
Client.close ()
Except
Client.close ()