Skip to content

Instantly share code, notes, and snippets.

@faelp22
Created May 10, 2019 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faelp22/3f7cef8e046c8668eff6152950383ff0 to your computer and use it in GitHub Desktop.
Save faelp22/3f7cef8e046c8668eff6152950383ff0 to your computer and use it in GitHub Desktop.
Um simples exemplo de servidor socket com python
#!/usr/bin/env python3
# fonte http://pythonclub.com.br/upload-de-arquivos-com-socket-e-struct.html
import socket
import struct
host = "127.0.0.1"
port = 8001
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
while True:
novo_sock, cliente = sock.accept()
with novo_sock:
ouvir = novo_sock.recv(1024)
if ouvir != b'':
mensagem, nome, dados = ouvir.decode().split(":")
serializar = struct.Struct("{}s {}s".format(len(nome.split()[0]), int(dados.split()[0])))
novo_sock.send("Pode enviar!".encode())
dados = novo_sock.recv(1024)
nome, arquivo = serializar.unpack(dados)
novo_sock.send("Os dados do arquivo {} foram enviados.".format(nome.decode()).encode())
with open("receiver/{}".format(nome.decode()), 'wb') as novo_arquivo:
novo_arquivo.write(arquivo)
print("Arquivo {} salvo em arquivos_recebidos.".format(nome.decode()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment