forked from ctb/cse491-serverz
/
server.py
153 lines (135 loc) · 4.79 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python
import argparse
from app import make_app
import imageapp
import os
import quixote
from quixote.demo.altdemo import create_publisher
import random
import socket
from StringIO import StringIO
from sys import stderr
import time
from urlparse import urlparse
from wsgiref.validate import validator
def handle_connection(conn, port):
request = conn.recv(1)
if not request:
print 'Error, remote client closed connection without sending anything'
return
count = 0
env = {}
while request[-4:] != '\r\n\r\n':
request += conn.recv(1)
request, data = request.split('\r\n',1)
headers = {}
for line in data.split('\r\n')[:-2]:
k, v = line.split(': ', 1)
headers[k.lower()] = v
path = urlparse(request.split(' ', 3)[1])
env['REQUEST_METHOD'] = 'GET'
env['PATH_INFO'] = path[2]
env['QUERY_STRING'] = path[4]
env['CONTENT_TYPE'] = 'text/html'
env['CONTENT_LENGTH'] = str(0)
env['SCRIPT_NAME'] = ''
env['SERVER_NAME'] = socket.getfqdn()
env['SERVER_PORT'] = str(port)
env['wsgi.version'] = (1, 0)
env['wsgi.errors'] = stderr
env['wsgi.multithread'] = False
env['wsgi.multiprocess'] = False
env['wsgi.run_once'] = False
env['wsgi.url_scheme'] = 'http'
env['HTTP_COOKIE'] = headers['cookie'] if 'cookie' in headers.keys() else ''
body = ''
if request.startswith('POST '):
env['REQUEST_METHOD'] = 'POST'
env['CONTENT_LENGTH'] = headers['content-length']
env['CONTENT_TYPE'] = headers['content-type']
while len(body) < int(headers['content-length']):
body += conn.recv(1)
def start_response(status, response_headers):
conn.send('HTTP/1.0 ')
conn.send(status)
conn.send('\r\n')
for pair in response_headers:
key, header = pair
conn.send(key + ': ' + header + '\r\n')
conn.send('\r\n')
env['wsgi.input'] = StringIO(body)
my_app = make_app()
validator_app = validator(my_app)
result = my_app(env, start_response)
for data in result:
conn.send(data)
conn.close()
def get_args():
app_list = ['altdemo', 'image', 'myapp', 'quotes', 'chat']
parser = argparse.ArgumentParser()
parser.add_argument('-A', action="store",
dest='arg_app',
help="The application to run")
parser.add_argument('-p', action="store",
default=0,
dest='arg_port',
help="The port to use (optional)",
required=False,
type=int)
results = parser.parse_args()
if results.arg_app not in app_list:
print '\nError, that application does not exist\n'
exit()
return results.arg_app, results.arg_port
def main(socketmodule=None):
if socketmodule is None:
socketmodule = socket
app, port = get_args()
if app == 'myapp':
s = socketmodule.socket()
host = socketmodule.getfqdn()
if port == 0:
port = random.randint(8000, 9999)
s.bind((host, port))
print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)
s.listen(5)
print 'Entering infinite loop; hit CTRL-C to exit'
while True:
c, (client_host, client_port) = s.accept()
print 'Got connection from', client_host, client_port
handle_connection(c, client_port)
elif app == 'image':
imageapp.setup()
p = imageapp.create_publisher()
wsgi_app = quixote.get_wsgi_app()
from wsgiref.simple_server import make_server
host = socketmodule.getfqdn()
if port == 0:
port = random.randint(8000, 9999)
httpd = make_server('', port, wsgi_app)
print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)
try:
httpd.serve_forever()
finally:
imageapp.teardown()
elif app == 'altdemo':
p = create_publisher()
wsgi_app = quixote.get_wsgi_app()
from wsgiref.simple_server import make_server
host = socketmodule.getfqdn()
if port == 0:
port = random.randint(8000, 9999)
p.is_thread_safe = True
httpd = make_server('', port, wsgi_app)
print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)
httpd.serve_forever()
elif app in ('quotes', 'chat'):
if port == 0:
port = random.randint(8000, 9999)
os.chdir(app)
os.system("python2.7 %s-server %d" % (app, port))
if __name__ == '__main__':
main()