-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.py
More file actions
62 lines (56 loc) · 1.71 KB
/
protocol.py
File metadata and controls
62 lines (56 loc) · 1.71 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
import struct
import os
chunksize=8192
# Protocol for sending a message independent of data Size
# Sends message length (in 4 bytes) followed by message data
def send_one_message(sock, data):
length = len(data)
sock.sendall(struct.pack('!I', length))
sock.sendall(data)
# Protocol for sending a file
# Sends file size (in 4 bytes) followed by file data
# Input:
# Socket, Full path of file to be sent
def send_one_file(sock,file_path):
statinfo = os.stat(file_path)
length = statinfo.st_size
send_one_message(sock,str(length))
f=open (file_path, "rb")
remain=int(length)
while (remain>0):
if (remain<chunksize):
l = f.read(remain)
else:
l = f.read(chunksize)
send_one_message(sock,l)
remain=remain-chunksize
# Protocol for receiving a message independent of data Size
# Receives message length (in 4 bytes) followed by message data
def recv_one_message(sock):
lengthbuf = recvall(sock, 4)
length, = struct.unpack('!I', lengthbuf)
return recvall(sock, length)
# Protocol for receiving a file
# Receives file size (in 4 bytes) followed by file data
# Input:
# Socket, Full path of file to be sent
def recv_one_file(sock,filename):
filesize=recv_one_message(sock)
open(filename, 'w').close()
with open(filename, "a") as f:
remain=int(filesize)
while (remain>0):
l = recv_one_message(sock)
f.write(l)
remain=remain-chunksize
# Receives data
# Input:
# Socket, Number of bytes to receive
def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf