Last active
October 5, 2022 19:37
-
-
Save junian/99e402db918cbe150002dc8c6736feb6 to your computer and use it in GitHub Desktop.
Simple HTTP server and client implementation in python
This file contains hidden or 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
#!/usr/bin/env python | |
import httplib | |
import sys | |
#get http server ip | |
http_server = sys.argv[1] | |
#create a connection | |
conn = httplib.HTTPConnection(http_server) | |
while 1: | |
cmd = raw_input('input command (ex. GET index.html): ') | |
cmd = cmd.split() | |
if cmd[0] == 'exit': #tipe exit to end it | |
break | |
#request command to server | |
conn.request(cmd[0], cmd[1]) | |
#get response from server | |
rsp = conn.getresponse() | |
#print server response and data | |
print(rsp.status, rsp.reason) | |
data_received = rsp.read() | |
print(data_received) | |
conn.close() |
This file contains hidden or 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
#!/usr/bin/env python | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
import os | |
#Create custom HTTPRequestHandler class | |
class KodeFunHTTPRequestHandler(BaseHTTPRequestHandler): | |
#handle GET command | |
def do_GET(self): | |
rootdir = 'c:/xampp/htdocs/' #file location | |
try: | |
if self.path.endswith('.html'): | |
f = open(rootdir + self.path) #open requested file | |
#send code 200 response | |
self.send_response(200) | |
#send header first | |
self.send_header('Content-type','text-html') | |
self.end_headers() | |
#send file content to client | |
self.wfile.write(f.read()) | |
f.close() | |
return | |
except IOError: | |
self.send_error(404, 'file not found') | |
def run(): | |
print('http server is starting...') | |
#ip and port of servr | |
#by default http server port is 80 | |
server_address = ('127.0.0.1', 80) | |
httpd = HTTPServer(server_address, KodeFunHTTPRequestHandler) | |
print('http server is running...') | |
httpd.serve_forever() | |
if __name__ == '__main__': | |
run() | |
This file contains hidden or 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
<head> | |
<title>Dummy HTML</title> | |
</head> | |
<body> | |
<h1>This is Awesome</h1> | |
<h1>You're awesome</h1> | |
</body> |
How to change this code to python3 format ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wish you had do_POST as well so I could learn it too