Created
June 25, 2012 21:05
-
-
Save thomasballinger/2991235 to your computer and use it in GitHub Desktop.
simple Python server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""An externally-accessible toy server""" | |
import socket | |
def get_local_address_hack(): | |
s = socket.socket() | |
s.connect(('google.com', 80)) | |
address, port = s.getsockname() | |
return address | |
def boring_response(client_socket): | |
print 'formulating response...' | |
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) | |
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) | |
while True: | |
s.blocking_listen(boring_response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment