Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SM_PIP_HomeWork2_HTTPserver #138

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions sm_assignments/sm_session02/http_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import socket
import sys
import os
import mimetypes


def response_ok(body=b"this is a pretty minimal response", mimetype=b"text/plain"):
"""returns a basic HTTP response"""
resp = []
resp.append(b"HTTP/1.1 200 OK")
# resp.append(b"Content-Type: text/plain")
resp.append(b"Content-Type: " + mimetype)
resp.append(b"")
resp.append(body)
# resp.append(body.encode('utf8'))
return b"\r\n".join(resp)


def response_method_not_allowed():
"""returns a 405 Method Not Allowed response"""
resp = []
resp.append("HTTP/1.1 405 Method Not Allowed")
resp.append("")
return "\r\n".join(resp).encode('utf8')


def response_not_found():
"""returns a 404 Not Found response"""
resp = []
resp.append("HTTP/1.1 404 Not Found")
resp.append("")
return "\r\n".join(resp).encode('utf8')
# return b""


def parse_request(request):
first_line = request.split("\r\n", 1)[0]
method, uri, protocol = first_line.split()
if method != "GET":
raise NotImplementedError("We only accept GET")
return uri


def resolve_uri(uri):
"""This method should return appropriate content and a mime type"""
webroot = "/webroot/"
path = os.getcwd() + webroot + uri
if os.path.isdir(uri):
content = str(os.listdir(path)).encode('utf8')
mimetype = b'text/plain'
return(content, mimetype)
elif os.path.isfile(path):
with open(path, 'rb') as f1:
content = f1.read()
mimetype = mimetypes.guess_type(path)[0]
return(content, mimetype.encode('utf8'))
else:
raise NameError("Not a valid file or directory")
# return b"still broken", b"text/plain"


def server(log_buffer=sys.stderr):
address = ('127.0.0.1', 10000)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("making a server on {0}:{1}".format(*address), file=log_buffer)
sock.bind(address)
sock.listen(1)

try:
while True:
print('waiting for a connection', file=log_buffer)
conn, addr = sock.accept() # blocking
try:
print('connection - {0}:{1}'.format(*addr), file=log_buffer)
request = ''
while True:
data = conn.recv(1024)
request += data.decode('utf8')
if len(data) < 1024:
break
try:
uri = parse_request(request)
except NotImplementedError:
response = response_method_not_allowed()
else:
try:
content, mime_type = resolve_uri(uri)
except NameError:
response = response_not_found()
else:
response = response_ok(content, mime_type)

print('sending response', file=log_buffer)
conn.sendall(response)
finally:
conn.close()

except KeyboardInterrupt:
sock.close()
return


if __name__ == '__main__':
server()
sys.exit(0)
44 changes: 44 additions & 0 deletions sm_assignments/sm_session02/simple_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import socket
import sys


def bytes_client(msg):
server_address = ('localhost', 10000)
sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP
)
print(
'connecting to {0} port {1}'.format(*server_address),
file=sys.stderr
)
sock.connect(server_address)
response = b''
done = False
bufsize = 1024
try:
print('sending "{0}"'.format(msg), file=sys.stderr)
sock.sendall(msg.encode('utf8'))
while not done:
chunk = sock.recv(bufsize)
if len(chunk) < bufsize:
done = True
response += chunk
print('received "{0}"'.format(response), file=sys.stderr)
finally:
print('closing socket', file=sys.stderr)
sock.close()
return response


def client(msg):
return bytes_client(msg).decode('utf8')


if __name__ == '__main__':
if len(sys.argv) != 2:
usg = '\nusage: python echo_client.py "this is my message"\n'
print(usg, file=sys.stderr)
sys.exit(1)

msg = sys.argv[1]
client(msg)
Loading