Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created June 25, 2012 21:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasballinger/2991211 to your computer and use it in GitHub Desktop.
Save thomasballinger/2991211 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""An externally-accessible toy server whith several response strategies"""
import socket
import sys
from multiprocessing import Pool
def web_scrape(site):
s = socket.socket()
s.connect((site, 1333))
s.send('GET / \r\n\r\n')
response_characters = []
while True:
print 'starting loop'
o = s.recv(1000)
if not o:
break
response_characters.append(o)
return "".join(response_characters)
def get_local_address_hack():
s = socket.socket()
s.connect(('google.com', 80))
address, port = s.getsockname()
return address
def long_running_request(client_socket):
print 'calculating complicated response...'
for x in xrange(10**8):
pass
print '...finished'
s = client_socket.recv(1000)
open('output.txt', 'a').write(s)
# I'm confused about what makes a valid http response
test_response = "HTTP/1.0 200 OK\r\n\r\n<html><body>This is a response!</body></html>"
client_socket.send(test_response)
client_socket.close()
class Server(object):
def __init__(self, port=8000):
self.address = get_local_address_hack()
self.port = port
self.socket = socket.socket()
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.address, self.port))
print 'ip to hit:'
print self.address,':', self.port
self.socket.listen(1)
def blocking_listen(self, response_function):
(client_socket, client_address) = self.socket.accept()
print 'client connected at ', client_address, 'connected'
response_function(client_socket)
def multiprocessing_listen(self, response_function, pool_size=3):
"""Takes a function(client_socket) to use for responses."""
self.pool = Pool(pool_size)
print 'starting listen loop'
while True:
(client_socket, client_address) = self.socket.accept()
print client_socket, 'at', client_address, 'connected'
self.pool.apply_async(response_function, [client_socket])
if __name__ == '__main__':
#print web_scrape('localhost')
#raw_input('wait while setup server again')
#s = '10.242.11.247'
#print web_scrape(s)
s = Server(8000)
s.blocking_listen(long_running_request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment