Created
September 3, 2021 11:55
-
-
Save thaisviana/ab2cbfb1320b63d281177e1bd1132489 to your computer and use it in GitHub Desktop.
arq_serve.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket, os | |
PORTA = 9091 | |
socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
host = socket.gethostbyname("") | |
socket_servidor.bind((host, PORTA)) | |
socket_servidor.listen() | |
print("Servidor de nome", host, "esperando conexão na porta", PORTA) | |
while True: | |
# Aceita alguma conexão | |
(socket_cliente,addr) = socket_servidor.accept() | |
print("Conectado a:", str(addr)) | |
# Recebe pedido do cliente: | |
msg = socket_cliente.recv(2048) | |
nome_arq = msg.decode('ascii') | |
print(nome_arq) | |
if os.path.isfile(nome_arq): | |
# Envia primeiro o tamanho | |
tamanho = os.stat(nome_arq).st_size | |
print(tamanho) | |
socket_cliente.send(str(tamanho).encode('ascii')) | |
# Abre o arquivo no modo leitura de bytes | |
arq = open(nome_arq, 'rb') | |
# Envia os dados | |
info_bytes = arq.read(4096) | |
while info_bytes: | |
socket_cliente.send(info_bytes) | |
info_bytes = arq.read(4096) | |
# Fecha o arquivo | |
arq.close() | |
else: | |
print("Não encontrou o arquivo") | |
# tamanho é -1 para indicar que não achou arquivo | |
socket_cliente.send(b'-1') | |
# Fecha o socket cliente | |
socket_cliente.close() | |
# Fecha o socket servidor | |
socket_servidor.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment