Creating simple http server

#1

if you want to test a simple http server either on local server or global server you can just copy the below code and run it on your machine.If you want to test with global server then change the ip address instead of local host.

from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse, json

class GetHandler(BaseHTTPRequestHandler):

def do_GET(self):
    parsed_path = urlparse.urlparse(self.path)
    message = '\n'.join([
        'CLIENT VALUES:',
        'client_address=%s (%s)' % (self.client_address,
            self.address_string()),
        'command=%s' % self.command,
        'posted content=%s' % self.path[1:],
        '',
        ])
    self.send_response(200)
    self.end_headers()
    self.wfile.write(message)
    return

def do_POST(self):
    content_len = int(self.headers.getheader('content-length'))
    post_body = self.rfile.read(content_len)
    self.send_response(200)
    self.end_headers()

    data = json.loads(post_body)

    self.wfile.write(data['foo'])
    return

if name == ‘main’:
from BaseHTTPServer import HTTPServer
server = HTTPServer((‘localhost’, 8080), GetHandler)
print ‘Starting server at http://localhost:8080
server.serve_forever()

its a python 2.7 code you can run it through sudo python code.py

If you want to run it on global server then you have to enable the port by typing sudo ufw allow
you have to check the port is enabled or not by sudo ufw status numbered.
this is a simple code for get and post requests for http.
for checking go to the browser enter the ip and port number and any input it will be displayed on your terminal and browser too.close the program by pressing ctrl+c for killing the process.other wise your port may get block

1 Like

Creating simple UDP server and client
Creating simple tcp server