Skip to content

Commit

Permalink
UDP add
Browse files Browse the repository at this point in the history
  • Loading branch information
May199 committed Apr 18, 2021
1 parent 010c4e8 commit d9b5649
Show file tree
Hide file tree
Showing 7 changed files with 131 additions and 63 deletions.
Binary file added UDP/Client/Relatório - Servidor WEB.pdf
Binary file not shown.
Binary file added UDP/Client/Transmissão Confiável de Dados.pdf
Binary file not shown.
60 changes: 60 additions & 0 deletions UDP/Client/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import socket
import os
import time


class Client():

def __init__(self, address = 'localhost', port = 3000):
self.address = address
self.port = port

def connect(self):

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.connect((self.address, self.port))

# Enviando arquivos ao servidor
# Pegar os arquivos que estão na pasta Cliente irá enviar para o server, depois que o user escolher o arquivo
# Será baixado e enviado para pasta Server
file_path = os.listdir()
print('Sending file names...')
for file in file_path:
server.sendall(file.encode())

server.sendall('closed'.encode())

print('Waiting for server response...')
msg = server.recv(4)
index = int.from_bytes(msg, 'little')

# Abrindo arquivos para enviar, depois claro da escolha do usuário de qual arquivo receber
file = open(file_path[index], 'rb')
file_size = os.path.getsize(file_path[index])
packet_kilobytes = 1024
packet_bytes = packet_kilobytes * 8

packet = (file_size // packet_bytes) + 1
server.sendall(packet.to_bytes(4, 'little'))

# Enviando pacotes
delay = 0.004
estimated_time = packet *(delay*1.2)

print(f'Sent {packet} packet to server')
print(f'Estimated time: {round(estimated_time)} seconds')


for i in range(packet):
pk = file.read(packet_bytes)
server.sendall(pk)
sent = f' {int((i+1)*packet_kilobytes)} | {int(packet_kilobytes*packet )}kb'
print(sent, end='')

time.sleep(delay)

file.close()
server.close()
if __name__ == '__main__':
cn = Client()
cn.connect()
71 changes: 71 additions & 0 deletions UDP/Server/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# UDP
# Protocolo que não se basea em uma conexão em que se manda dados sem segurança com relação ao seu ddestino.
import socket
import time

class Server:

def __init__(self, address = 'localhost', port = 3000):
self.address = address
self.port = port

def connect(self):
#Criando socket com o protocolo UDP utilizando 'SOCK_DGRAM'

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
# Bind() só recebe 1 paramentro então utilizando as (()) conseguimos burlar isso já que teoricamente é apenas 1
server.bind((self.address, self.port))

# Esperando receber lista de arquivos do cliente
print('Connecting to server')
files = []

while True:
data, addressConection = server.recvfrom(1024)

if data.decode() == "closed":
break
filename = data.decode()
print(f'[{len(files)}] {filename}')
files.append(filename)

# Escolhendo arquivo que vou querer baixar do cliente
fileselect = int(input('\n Which file do you want to receive?'))
while not (0 <= fileselect < len(files)):
print('Opção inválida!')
fileselect = int(input('\n Which file do you want to receive?'))

server.sendto(fileselect.to_bytes(4, 'little'), addressConection)
# Recebendo numero de pacotes
# Queremos saber em quantos pacotes o arquivo sera enviado
data = server.recv(4)
packet = int.from_bytes(data, 'little')

# Recebendo pacotes
server.settimeout(5)
file = open(files[fileselect], 'wb')
packet_kilobytes = 1024
packet_bytes = packet_kilobytes * 8

print(f'Recebendo {packet} pacotes...')

start = time.time()
for i in range(packet):
data = server.recv(packet_bytes)
file.write(data)

time_download = f'Downloading ...{round((100*(i+1))/packet, 2)}%'
print('\r'+time_download, end='')

total_time = round(time.time()-start, 2)
print(f'\n Download complete: {total_time} seconds')

server.close()

if __name__ == '__main__':
sr = Server()
sr.connect()




27 changes: 0 additions & 27 deletions UDP/client.py

This file was deleted.

5 changes: 0 additions & 5 deletions UDP/main.py

This file was deleted.

31 changes: 0 additions & 31 deletions UDP/server.py

This file was deleted.

0 comments on commit d9b5649

Please sign in to comment.