Skip to content

Commit f2d1b72

Browse files
committed
Week 2 Assignments
1 parent 03c1122 commit f2d1b72

4 files changed

Lines changed: 307 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python
2+
3+
import socket
4+
5+
host = '' # listen on all connections (WiFi, etc)
6+
port = 50000
7+
backlog = 5 # how many connections can we stack up
8+
size = 1024 # number of bytes to receive at once
9+
10+
http = """
11+
<html> <body> \
12+
<h1>This is a header</h1> \
13+
<p> \
14+
and this is some regular text \
15+
</p> \
16+
<p> \
17+
and some more \
18+
</p> \
19+
</body> \
20+
</html> """
21+
22+
23+
## create the socket
24+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25+
# set an option to tell the OS to re-use the socket
26+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
27+
28+
# the bind makes it a server
29+
s.bind( (host,port) )
30+
s.listen(backlog)
31+
32+
while True: # keep looking for new connections forever
33+
client, address = s.accept() # look for a connection
34+
data = client.recv(size)
35+
if data: # if the connection was closed there would be no data
36+
print "received: %s, sending it back"%data
37+
client.send(http)
38+
client.close()
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env python
2+
3+
import socket
4+
import httplib
5+
import sys, os
6+
7+
8+
9+
class EchoServer(object):
10+
"""Interacts with Client, recieving and sending data."""
11+
12+
def __init__(self, host='', port=50000, backlog=5):
13+
"""Constructs the socket connection, configures the server."""
14+
15+
# Create a TCP/IP socket
16+
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
17+
# Bind the socket to the port
18+
self.server.bind((host, port))
19+
print 'Server started on port: ', port
20+
# Listen for incoming connections
21+
self.server.listen(backlog)
22+
print("Server listening\n")
23+
## create the socket
24+
# set an option to tell the OS to re-use the socket
25+
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
26+
27+
self.size = 1024 # number of bytes to receive at once
28+
29+
def ProcessRequest(self, size):
30+
# Wait for a connection
31+
self.con, self.cli = self.server.accept()
32+
print 'New connection from ', self.cli
33+
self.data = self.con.recv(size)
34+
print "Client Request: " + self.data
35+
return self.data
36+
37+
def ProcessResponse(self, data):
38+
# Send data to client
39+
self.con.send(data)
40+
41+
def CloseSocket(self):
42+
self.con.close()
43+
44+
def Payload(self):
45+
self.body = """
46+
<html> <body> \
47+
<h1>This is a header</h1> \
48+
<p> \
49+
and this is some regular text \
50+
</p> \
51+
<p> \
52+
and some more \
53+
</p> \
54+
</body> \
55+
</html> """
56+
return self.body
57+
58+
def Response(self):
59+
body = self.Payload()
60+
ok = "HTTP/1.1 200 OK"
61+
empty = ""
62+
resp = "\r\n".join([ok, empty, body])
63+
return resp
64+
65+
def ParseRequest(data):
66+
for line in data:
67+
if "GET" in line:
68+
print "FOUND GET"
69+
70+
71+
def main():
72+
echo_server = EchoServer()
73+
while True:
74+
data = echo_server.ProcessRequest(echo_server.size)
75+
try:
76+
if data: # if the connection was closed there would be no data
77+
echo_server.ProcessResponse(echo_server.Response())
78+
finally:
79+
print "Closing Socket"
80+
echo_server.CloseSocket()
81+
82+
main()
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python
2+
3+
import socket
4+
import httplib
5+
import sys, os
6+
7+
8+
class EchoServer(object):
9+
"""Interacts with Client, recieving and sending data."""
10+
11+
def __init__(self, host='', port=50001, backlog=5):
12+
"""Constructs the socket connection, configures the server."""
13+
14+
# Create a TCP/IP socket
15+
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16+
# Bind the socket to the port
17+
self.server.bind((host, port))
18+
print 'Server started on port: ', port
19+
# Listen for incoming connections
20+
self.server.listen(backlog)
21+
print("Server listening\n")
22+
## create the socket
23+
# set an option to tell the OS to re-use the socket
24+
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
25+
26+
self.size = 1024 # number of bytes to receive at once
27+
28+
def ProcessRequest(self, size):
29+
# Wait for a connection
30+
self.con, self.cli = self.server.accept()
31+
print 'New connection from ', self.cli
32+
self.data = self.con.recv(size)
33+
return self.data
34+
35+
def ProcessResponse(self, data):
36+
# Send data to client
37+
self.con.send(data)
38+
39+
def CloseSocket(self):
40+
self.con.close()
41+
42+
def ParseRequest(self, request):
43+
i = request.split()
44+
(verb, http) = i[0], i[2]
45+
return (verb, http)
46+
47+
def Payload(self, body):
48+
body = """
49+
<html> <body> \
50+
<h1>""" + body + """</h1> \
51+
</body> </html> """
52+
return body
53+
54+
def ClientErrorResponse(self):
55+
bad = "HTTP/1.1 400 Bad Request"
56+
body = self.Payload(bad)
57+
empty = ""
58+
resp = "\r\n".join([bad, empty, body])
59+
return resp
60+
61+
def Response(self):
62+
ok = "HTTP/1.1 200 OK"
63+
body = self.Payload(ok)
64+
empty = ""
65+
resp = "\r\n".join([ok, empty, body])
66+
return resp
67+
68+
69+
def main():
70+
echo_server = EchoServer()
71+
while True:
72+
data = echo_server.ProcessRequest(echo_server.size)
73+
try:
74+
if data: # if the connection was closed there would be no data
75+
(verb, http) = echo_server.ParseRequest(data)
76+
if verb == 'GET' and http == "HTTP/1.1":
77+
echo_server.ProcessResponse(echo_server.Response())
78+
else:
79+
echo_server.ProcessResponse(echo_server.ClientErrorResponse())
80+
raise ValueError('%s %s is a bad request' % (verb, http))
81+
finally:
82+
print "Closing Socket"
83+
echo_server.CloseSocket()
84+
85+
main()
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#!/usr/bin/env python
2+
3+
import socket
4+
import httplib
5+
import os
6+
7+
8+
class EchoServer(object):
9+
"""Interacts with Client, recieving and sending data."""
10+
11+
def __init__(self, host='', port=50001, backlog=5):
12+
"""Constructs the socket connection, configures the server."""
13+
14+
# Create a TCP/IP socket
15+
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16+
# Bind the socket to the port
17+
self.server.bind((host, port))
18+
print 'Server started on port: ', port
19+
# Listen for incoming connections
20+
self.server.listen(backlog)
21+
print("Server listening\n")
22+
## create the socket
23+
# set an option to tell the OS to re-use the socket
24+
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
25+
26+
self.size = 1024 # number of bytes to receive at once
27+
28+
def ProcessRequest(self, size):
29+
# Wait for a connection
30+
self.con, self.cli = self.server.accept()
31+
print 'New connection from ', self.cli
32+
self.data = self.con.recv(size)
33+
return self.data
34+
35+
def ProcessResponse(self, data):
36+
# Send data to client
37+
self.con.send(data)
38+
39+
def CloseSocket(self):
40+
self.con.close()
41+
42+
def ParseRequest(self, request):
43+
i = request.split()
44+
print i
45+
(verb, path, http) = i[0], i[1], i[2]
46+
return (verb, path, http)
47+
48+
def Payload(self, header, body):
49+
body = """
50+
<html> <body> \
51+
<h1>""" + header + """</h1> \
52+
<p>""" + body + """</p> \
53+
</body> </html> """
54+
return body
55+
56+
def ClientErrorResponse(self):
57+
bad = "HTTP/1.1 400 Bad Request"
58+
body = self.Payload(bad)
59+
empty = ""
60+
resp = "\r\n".join([bad, empty, body])
61+
return resp
62+
63+
def NotFoundResponse(self):
64+
notfound = "HTTP/1.1 404 Not Found"
65+
body = self.Payload(notfound)
66+
empty = ""
67+
resp = "\r\n".join([notfound, empty, body])
68+
return resp
69+
70+
def Response(self, data=''):
71+
ok = "HTTP/1.1 200 OK"
72+
body = self.Payload(ok, data)
73+
empty = ""
74+
resp = "\r\n".join([ok, empty, body])
75+
return resp
76+
77+
def ResolveUri(self, path):
78+
if os.path.realpath.exists(path):
79+
content = os.listdir(path)
80+
return content
81+
82+
def main():
83+
echo_server = EchoServer()
84+
while True:
85+
data = echo_server.ProcessRequest(echo_server.size)
86+
try:
87+
if data: # if the connection was closed there would be no data
88+
(verb, path, http) = echo_server.ParseRequest(data)
89+
resolve_uri = echo_server.ResolveUri(path)
90+
if verb == 'GET' and http == "HTTP/1.1":
91+
print echo_server.ResolveUri(path)
92+
echo_server.ProcessResponse(echo_server.Response())
93+
# return echo_server.NotFoundResponse()
94+
# raise ValueError('%s was not found' % (path))
95+
else:
96+
echo_server.ProcessResponse(echo_server.ClientErrorResponse())
97+
raise ValueError('%s %s is a bad request' % (verb, http))
98+
finally:
99+
print "Closing Socket"
100+
echo_server.CloseSocket()
101+
102+
main()

0 commit comments

Comments
 (0)