-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
113 lines (100 loc) · 3.69 KB
/
client.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
# echo-client.py
import socket
from time import sleep
from traceback import print_tb
import sys
# HOST = "127.0.0.1" # The server's hostname or IP address
# PORT = 65432 # The port used by the server
dir = "./ClientFiles"
inputfile = sys.argv[1]
def parse_file(file_name):
f = open(f"{file_name}", mode = "r")
commands = f.read().split("\n")
f.close()
return commands
cache = {}
def parse(cmd):
x = cmd.split()
ext = x[1].split(".")[1]
method = x[0]
file_name = x[1]
host = x[2]
if len(x) > 3:
port = x[3]
return method,file_name,host,port,ext
return method,file_name,host,80,ext
# x = sys.argv
# print(x[1])
commands = parse_file(inputfile)
for i in commands:
method , file_name, HOST, PORT, EXT = parse(i)
request = f"{method} /{file_name} HTTP/1.0\r\nHOST: {HOST}:{PORT}\r\n\r\n"
if request in cache:
if EXT == "png":
print("This file is located in the cache")
x = cache.get(request)
#print(x)
x1 = x.split(b"\r\n\r\n")[0].decode()
print(x1)
x2 = x.split(b"\r\n\r\n")[1]
print(x2)
#f = open(f"{dir}/{file_name}", mode="rb")
#file = f.read()
#f.close()
else:
print("This file is located in the cache")
x = cache.get(request)
x1 = x.split("\r\n\r\n")[0]
print(x1)
x2 = x.split("\r\n\r\n")[1]
print(x2)
# f = open(f"{dir}/{file_name}", mode="r")
# file = f.read()
# f.close()
else:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print(f"Starting socket connection with {HOST}:{PORT}")
s.connect((str(HOST), int(PORT)))
if method == "GET":
# request = f"{method} /{file_name} HTTP/1.1\r\nHOST: {HOST}:{PORT}\r\n\r\n"
s.sendall(request.encode())
buff = b""
while True:
data = s.recv(1000000)
if not data:
break
buff = buff + data
data = buff
print("Waiting for data from server....")
if EXT == "png":
f = open(f"{dir}/{file_name}", mode="wb+")
file_png = data.split(b"\r\n\r\n")[1]
file = f.write(file_png)
f.close()
cache[request]=data
else:
f = open(f"{dir}/{file_name}", mode="w")
content = data.split(b"\r\n\r\n")[1]
file = f.write(content.decode())
f.close()
cache[request]=data.decode()
#print(f"{data.decode()}")
elif method == "POST":
try:
if EXT == "png":
f = open(f"{dir}/{file_name}", mode="rb")
file = f.read()
f.close()
request = f"POST /{file_name} HTTP/1.0\r\nHOST: {HOST}:{PORT}\r\n\r\n"
request = request.encode()
request = request + file
else:
f = open(f"{dir}/{file_name}",mode ="r")
file = f.read()
f.close()
request = f"POST /{file_name} HTTP/1.0\r\nHOST: {HOST}:{PORT}\r\n\r\n{file}"
request = request.encode()
s.sendall(request)
except IOError:
print("FILE NOT FOUND")
# sleep(10)