-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.py
More file actions
71 lines (63 loc) · 2.63 KB
/
Copy pathServer.py
File metadata and controls
71 lines (63 loc) · 2.63 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
'''
Script for server
@author: hao
'''
import config
import protocol
import os
from socket import *
class server:
# Constructor: load the server information from config file
def __init__(self):
self.port, self.path=config.config().readServerConfig()
# Get the file names from shared directory
def getFileList(self):
return os.listdir(self.path)
# Function to send file list to client
def listFile(self, serverSocket):
serverSocket.send(protocol.prepareFileList(protocol.HEAD_LIST, self.getFileList()))
# Function to send a file to client
def sendFile(self,serverSocket,fileName):
f = open(fileName,'rb')
l = f.read(1024) # each time we only send 1024 bytes of data
while (l):
serverSocket.send(l)
l = f.read(1024)
#=======================================================================================================================================
def recieveFile(self,serverSocket,fileName):
with open(fileName, 'wb') as f:
print ('file opened')
while True:
#print('receiving data...')
data = serverSocket.recv(1024)
#print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
#=======================================================================================================================================
# Main function of server, start the file sharing service
def start(self):
serverPort=self.port
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(20)
print('The server is ready to receive')
while True:
connectionSocket, addr = serverSocket.accept()
dataRec = connectionSocket.recv(1024)
header,msg=protocol.decodeMsg(dataRec.decode()) # get client's info, parse it to header and content
# Main logic of the program, send different content to client according to client's requests
if(header==protocol.HEAD_REQUEST):
self.listFile(connectionSocket)
elif(header==protocol.HEAD_DOWNLOAD):
self.sendFile(connectionSocket, self.path+"/"+msg)
elif(header==protocol.HEAD_UPLOAD):
self.recieveFile(connectionSocket, self.path+"/"+msg)
else:
connectionSocket.send(protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
connectionSocket.close()
def main():
s=server()
s.start()
main()