-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetfile.py
76 lines (65 loc) · 1.98 KB
/
getfile.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
import sys, os, time, _thread as thread
from socket import *
blksz = 1024
defaultHost = 'localhost'
defaultPort = 50001
helptext = """
Usage...
server=> getfile.py -mode server [-port nnn][-host -hhh|localhost]
client=> getfile.py [-mode client] -file fff [-port nnn][-host -hhh|localhost]"""
def now():
return time.asctime()
def parsecommandline():
dict = {}
args = sys.argv[1:]
while len(args) >= 2:
dict[args[0]] = args[1]
args = args[2:]
return dict
def client(host, port, filename):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send((filename + '\n').encode())
dropdir = os.path.split(filename)[1]
file = open(dropdir, 'wb')
while True:
data = sock.recv(blksz)
if not data: break
file.write(data)
sock.close()
file.close()
print('Clinet got', filename, 'at', now())
def serverthread(clientsock):
sockfile = clientsock.makefile('r')
filename = sockfile.readline()[:-1]
try:
file = open(filename, 'rb')
while True:
bytes = file.read(blksz)
if not bytes: break
sent = clientsock.send(bytes)
assert sent == len(bytes)
except:
print('Error downloading file on server:', filename)
clientsock.close()
def server(host, port):
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind((host, port))
serversock.listen(5)
while True:
clientsock, clientaddr = serversock.accept()
print('Server connected by', clientaddr, 'at', now())
thread.start_new_thread(serverthread, (clientsock,))
def main(args):
host = args.get('-host', defaultHost)
port = int(args.get('-port', defaultPort))
if args.get('-mode') == 'server':
if host == 'localhost': host = ''
server(host, port)
elif args.get('-file'):
client(host, port, args['-file'])
else:
print(helptext)
if __name__ == '__main__':
args = parsecommandline()
main(args)