forked from kathryntanardy/Web_Proxy_Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
48 lines (34 loc) · 1.26 KB
/
proxy.py
File metadata and controls
48 lines (34 loc) · 1.26 KB
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
import socket
import threading
cache = {}
def client_request(clientSocket):
request = clientSocket.recv(1024).decode()
request_split = request.split('\r\n')
request_line = request_split[0]
print(request_line)
# Check if in cache
if request in cache:
print('Cache Hit!\n')
clientSocket.send(cache[request].encode())
else:
print('Cache Miss!\n')
clientSocketOrigin = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocketOrigin.connect(('127.0.0.1', 1200))
clientSocketOrigin.send(request.encode())
replyFromOrigin = clientSocketOrigin.recv(1024).decode()
cache[request] = replyFromOrigin
clientSocket.sendall(replyFromOrigin.encode())
clientSocketOrigin.close()
clientSocket.close()
def initiate_proxy():
serverPort = 8080
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('127.0.0.1', serverPort))
serverSocket.listen(5)
print(f"Proxy server is running.")
while True:
(clientSocket, address) = serverSocket.accept()
thread = threading.Thread(target=client_request, args=(clientSocket,))
thread.start()
if __name__ == '__main__':
initiate_proxy()