-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketcase2.py
55 lines (46 loc) · 1.07 KB
/
socketcase2.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
#!/bin/env python
import socket
# Address
HOST = ''
PORT = 8000
# Prepare HTTP response
text_content = '''HTTP/1.x 200 OK
Content-Type: text/html
<head>
<title>WOW</title>
</head>
<html>
<p>Wow, Python Server</p>
<IMG src="test.png"/>
</html>
'''
# Read picture, put into HTTP format
f = open('test.png','rb')
pic_content = '''
HTTP/1.x 200 OK
Content-Type: image/png
'''
pic_content = pic_content + f.read()
f.close()
# Configure socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
# infinite loop, server forever
while True:
# 3: maximum number of requests waiting
s.listen(3)
conn, addr = s.accept()
request = conn.recv(1024)
method = request.split(' ')[0]
src = request.split(' ')[1]
# deal with GET method
if method == 'GET':
# ULR
if src == '/test.png':
content = pic_content
else: content = text_content
print 'Connected by', addr
print 'Request is:', '\n',request
conn.sendall(content)
# close connection
conn.close()