-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
99 lines (86 loc) · 2.7 KB
/
server.py
File metadata and controls
99 lines (86 loc) · 2.7 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
86
87
88
89
90
91
92
93
94
95
96
import socket
import thread
import sys
import os
import uuid
HOST = ''
PORT = 50005 # Port for the server recieve connections
def calcValue(fileName):
###Function that calculate the total value from products
##in the recieved file
totalValue = 0
file = open(fileName, "r")
lines = file.readlines()
for l in lines:
parts = l.split(",")
totalValue+=float(parts[1])*float(parts[2])
return totalValue
def get(con):
###Function that get the client file
###generate a unique name to the file
##The file will be save on RecievedFiles/
fileName = "RecievedFiles/"+str(uuid.uuid4())
try:
###Save the file on the server directory
#######################################################
file = open(fileName, 'wb')
con.send("READY")
print("Downloading file...")
while True:
d = con.recv(4096)
if (d=="--END--"):
file.close()
break
file.write(d)
con.send("SUCCES")
print("Succesfully downloaded file as "+fileName)
#######################################################
###Calculate the total value from the products and send
##the value to the client##############################
valorTotal = calcValue(fileName)
con.send(str(valorTotal))
#######################################################
###After it all, close the connection with the client
con.close()
except Exception as msg:
con.send("ERROR")
#File Error.
print("Error message: "+str(msg))
return
def conectado(con, cliente):
###Function that starts a new thread for the connection
msg = con.recv(1024)
if (msg=="GETFILE"):
print("Connection started with "+str(cliente))
get(con)
else:
con.close()
thread.exit()
###Create a socket that use IPV4 and TCP protocol
###Bind the port for this process conections
###Set the maximun number of queued connections
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
try:
tcp.bind(orig)
print("Bind succesfull!")
except socket.error as SBE:
print("Bind failed!")
print(SBE)
sys.exit()
tcp.listen(5)
print("TCP start.")
print("Listening...")
###Server accept connections until a keyboard interrupt
###If there is a keyboard interrupt, release the port
try:
while True:
con, cliente = tcp.accept()
##A thread will be create for each connection
#so, more than one client can be attended
thread.start_new_thread(conectado, tuple([con, cliente]))
except KeyboardInterrupt:
print("")
print("Stop listening and TCP closed.")
tcp.close()
sys.exit()