-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverUDP.py
More file actions
96 lines (70 loc) · 2.61 KB
/
serverUDP.py
File metadata and controls
96 lines (70 loc) · 2.61 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
'''
Created on Jan 17, 2020
@author: tiz
'''
'''
Created on Jan 17, 2020
@author: tiz
'''
from socket import *
from requests import *
import requests
import os
import sys
from timeit import default_timer as timer
serverPort = 4000
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.bind(('',serverPort))
#serverSocket.listen(1)
print 'The server is ready to receive'
while 1:
fileurl, clientAddress = serverSocket.recvfrom(2048)
#connectionSocket, addr = serverSocket.accept()
#fileurl = connectionSocket.recv(4000)
#Try to get the total time for the process
start = timer()
try:
r = requests.get(fileurl, allow_redirects=True)
r.raise_for_status()
except requests.exceptions.HTTPError as err:
print err
serverSocket.sendto('Http Error', clientAddress)
#connectionSocket.send('Http error')
sys.exit(1)
except requests.exceptions.ConnectionError as errcon:
print ("Error Connecting:",errcon)
serverSocket.sendto('Connection Error', clientAddress)
sys.exit(1)
except requests.exceptions.Timeout as errTime:
print ("Timeout Error:",errTime)
serverSocket.sendto('Timeout Error', clientAddress)
sys.exit(1)
# Check the file size
fileSize = r.headers['Content-length']
print 'Client request new file. Size of the file: ', fileSize
# Find the name of the file based on URL
if fileurl.find('/'):
print 'Getting ' + fileurl.rsplit('/', 1)[1]
fileToClient = fileurl.rsplit('/', 1)[1]
# Create an empty file to store the content of the file
open(fileToClient, 'wb').write(r.content)
#First: send the size of the file from the header to the client to compare
#connectionSocket.send(fileSize)
serverSocket.sendto(fileSize, clientAddress)
#Second send the file to client
#connectionSocket.send(fileToClient)
serverSocket.sendto(fileToClient, clientAddress)
# Then wait for the BYE message from the client in order to close
#byeMessage = connectionSocket.recv(4000)
byeMessage,clientAddress = serverSocket.recvfrom(2048)
print 'From client: ' , byeMessage
if byeMessage == 'BYE':
print 'BYE message arrived, closing connection'
# Now stop the timer, compute the elapsed time and send it to the client
end = timer()
totTime = (end - start)
print 'Total time: ', totTime, 'sec.'
print
#connectionSocket.send(str(timeTodw))
serverSocket.sendto(str(totTime), clientAddress)
#connectionSocket.close()