Last active
December 17, 2015 18:29
-
-
Save Sulverus/5653917 to your computer and use it in GitHub Desktop.
small http server fork.
with request split and user-agent output=)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from socket import * | |
LOG_MODE = True | |
DEFAULT_REPLY = '<h1>Hello world fork=)</h1>' | |
MAX_RECV = 1024 | |
def server_bind(port, max_conn): | |
s = socket(AF_INET, SOCK_STREAM) | |
s.bind(('', port)) | |
s.listen(max_conn) | |
return s | |
def response_template(message=DEFAULT_REPLY): | |
res = "HTTP/1.0 200 OK\r\n" | |
res += "Content-Length: %s\r\n" % len(message) | |
res += "Content-Type: text/html\r\n" | |
res += "\r\n" | |
res += message | |
res += "\r\n" | |
return res | |
def split_data(recv): | |
s = recv.split('\\r\\n') | |
sp_data = dict( (k, v) for k, v in (a.split(': ') for a in s[1:len(s)-2])) | |
return sp_data | |
def server_ioloop(s): | |
while True: | |
client, addr = s.accept() | |
recv = repr(client.recv(MAX_RECV)) | |
request = split_data(recv) | |
if LOG_MODE: | |
print("Connect from %s" % str(addr)) | |
print recv | |
if 'User-Agent' in request.keys(): | |
response = response_template(DEFAULT_REPLY+"<br>You are using: <b>%s</b>" % request['User-Agent']) | |
else: | |
response = response_template() | |
client.send(response.encode('ascii')) | |
client.close() | |
server_ioloop(server_bind(8888, 100)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment