Skip to content
Closed
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
52 changes: 42 additions & 10 deletions assignments/week01/lab/echo_client.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
import socket
#! /usr/bin/python

import sys
import socket


class EchoClient(object):
"""Interacts with Server, sending and recieving request data."""

def __init__(self, host='127.0.0.1', port=50000):
"""Constructs the socket connection, configures the client."""

# Create a TCP/IP socket
self.client = socket.socket(2, 1, 0)

# Connect the socket to the port where the server is listening
self.client.connect((host, port))

def MakeRequest(self, request):
# Send data to server
self.client.sendall(request)

# Create a TCP/IP socket
def UserInput(self):
value = raw_input("Add, Subtract, Multiply, or Divide two integers. (4 + 4) ")
return value

# Connect the socket to the port where the server is listening
server_address = ('localhost', 50000)
def FetchResult(self):
result = self.client.recv(1024)
return result

def CloseSocket(self):
return self.client.close()

try:
# Send data
message = 'This is the message. It will be repeated.'

# print the response
def main():
while True:
echo_client = EchoClient()
message = echo_client.UserInput()
try:
# send data
echo_client.MakeRequest(message)
# print the response
print echo_client.FetchResult()
finally:
print "Closing Socket"
echo_client.CloseSocket()

finally:
# close the socket to clean up
main()
61 changes: 51 additions & 10 deletions assignments/week01/lab/echo_server.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,60 @@
import socket
#! /usr/bin/python

import sys
import socket

# Create a TCP/IP socket

# Bind the socket to the port
server_address = ('localhost', 50000)
class EchoServer(object):
"""Interacts with Client, recieving and sending data."""

# Listen for incoming connections
def __init__(self, host="127.0.0.1", port=50000, backlog=5):
"""Constructs the socket connection, configures the server."""

while True:
# Create a TCP/IP socket
self.server = socket.socket(2, 1, 0)
# Bind the socket to the port
self.server.bind((host, port))
print 'Server started on port: ', port
# Listen for incoming connections
self.server.listen(backlog)
print("Server listening\n")

def ProcessRequest(self):
# Wait for a connection
self.con, self.cli = self.server.accept()
print 'New connection from ', self.cli
self.data = self.con.recv(1024)
print "Client Request: " + self.data
return self.data

def ProcessResponse(self, response):
# Send data to client
self.con.sendall('The result is ' + str(response))

try:
# Receive the data and send it back

def DoMath(self, data):
self.data = self.data.split()
if self.data[1] == '+':
result = int(self.data[0]) + int(self.data[2])
elif self.data[1] == '-':
result = int(self.data[0]) - int(self.data[2])
elif self.data[1] == '*':
result = int(self.data[0]) * int(self.data[2])
elif self.data[1] == '/':
result = int(self.data[0]) / int(self.data[2])
return result

def CloseSocket(self):
self.con.close()


def main():
echo_server = EchoServer()
while True:
data = echo_server.ProcessRequest()
try:
echo_server.ProcessResponse(echo_server.DoMath(data))
finally:
# Clean up the connection
print "Closing Socket"
echo_server.CloseSocket()

main()
38 changes: 38 additions & 0 deletions assignments/week02/lab/http_serve1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env python

import socket

host = '' # listen on all connections (WiFi, etc)
port = 50000
backlog = 5 # how many connections can we stack up
size = 1024 # number of bytes to receive at once

http = """
<html> <body> \
<h1>This is a header</h1> \
<p> \
and this is some regular text \
</p> \
<p> \
and some more \
</p> \
</body> \
</html> """


## create the socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set an option to tell the OS to re-use the socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# the bind makes it a server
s.bind( (host,port) )
s.listen(backlog)

while True: # keep looking for new connections forever
client, address = s.accept() # look for a connection
data = client.recv(size)
if data: # if the connection was closed there would be no data
print "received: %s, sending it back"%data
client.send(http)
client.close()
82 changes: 82 additions & 0 deletions assignments/week02/lab/http_serve2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env python

import socket
import httplib
import sys, os



class EchoServer(object):
"""Interacts with Client, recieving and sending data."""

def __init__(self, host='', port=50000, backlog=5):
"""Constructs the socket connection, configures the server."""

# Create a TCP/IP socket
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
self.server.bind((host, port))
print 'Server started on port: ', port
# Listen for incoming connections
self.server.listen(backlog)
print("Server listening\n")
## create the socket
# set an option to tell the OS to re-use the socket
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.size = 1024 # number of bytes to receive at once

def ProcessRequest(self, size):
# Wait for a connection
self.con, self.cli = self.server.accept()
print 'New connection from ', self.cli
self.data = self.con.recv(size)
print "Client Request: " + self.data
return self.data

def ProcessResponse(self, data):
# Send data to client
self.con.send(data)

def CloseSocket(self):
self.con.close()

def Payload(self):
self.body = """
<html> <body> \
<h1>This is a header</h1> \
<p> \
and this is some regular text \
</p> \
<p> \
and some more \
</p> \
</body> \
</html> """
return self.body

def Response(self):
body = self.Payload()
ok = "HTTP/1.1 200 OK"
empty = ""
resp = "\r\n".join([ok, empty, body])
return resp

def ParseRequest(data):
for line in data:
if "GET" in line:
print "FOUND GET"


def main():
echo_server = EchoServer()
while True:
data = echo_server.ProcessRequest(echo_server.size)
try:
if data: # if the connection was closed there would be no data
echo_server.ProcessResponse(echo_server.Response())
finally:
print "Closing Socket"
echo_server.CloseSocket()

main()
85 changes: 85 additions & 0 deletions assignments/week02/lab/http_serve3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python

import socket
import httplib
import sys, os


class EchoServer(object):
"""Interacts with Client, recieving and sending data."""

def __init__(self, host='', port=50001, backlog=5):
"""Constructs the socket connection, configures the server."""

# Create a TCP/IP socket
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
self.server.bind((host, port))
print 'Server started on port: ', port
# Listen for incoming connections
self.server.listen(backlog)
print("Server listening\n")
## create the socket
# set an option to tell the OS to re-use the socket
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

self.size = 1024 # number of bytes to receive at once

def ProcessRequest(self, size):
# Wait for a connection
self.con, self.cli = self.server.accept()
print 'New connection from ', self.cli
self.data = self.con.recv(size)
return self.data

def ProcessResponse(self, data):
# Send data to client
self.con.send(data)

def CloseSocket(self):
self.con.close()

def ParseRequest(self, request):
i = request.split()
(verb, http) = i[0], i[2]
return (verb, http)

def Payload(self, body):
body = """
<html> <body> \
<h1>""" + body + """</h1> \
</body> </html> """
return body

def ClientErrorResponse(self):
bad = "HTTP/1.1 400 Bad Request"
body = self.Payload(bad)
empty = ""
resp = "\r\n".join([bad, empty, body])
return resp

def Response(self):
ok = "HTTP/1.1 200 OK"
body = self.Payload(ok)
empty = ""
resp = "\r\n".join([ok, empty, body])
return resp


def main():
echo_server = EchoServer()
while True:
data = echo_server.ProcessRequest(echo_server.size)
try:
if data: # if the connection was closed there would be no data
(verb, http) = echo_server.ParseRequest(data)
if verb == 'GET' and http == "HTTP/1.1":
echo_server.ProcessResponse(echo_server.Response())
else:
echo_server.ProcessResponse(echo_server.ClientErrorResponse())
raise ValueError('%s %s is a bad request' % (verb, http))
finally:
print "Closing Socket"
echo_server.CloseSocket()

main()
Loading