Boa noite ,
segue uma solução para essa quetão,
Server
import socket
server = socket.socket()
file_name = "contato.txt"
try:
server.bind(("0.0.0.0", 111))
server.listen(5)
print("{0} Server On".format(server.getsockname()))
while True:
(client_socket, address) = server.accept()
print("Con: {0}".format(address))
try:
while True:
data = client_socket.recv(1024)
data_processed = bytes.decode(data).strip()
if data_processed == "1":
file = open(file_name, 'a+')
data_rec = client_socket.recv(1024)
data_rec_processed = bytes.decode(data_rec).strip() + "\n"
file.write(data_rec_processed)
file.close()
elif data_processed == "2":
file = open(file_name, 'rb')
client_socket.send(file.read())
file.close()
elif data_processed == "3":
client_socket.send(str.encode("Saindo....\ntchau(^_^)/\n"))
client_socket.close()
break
except Exception as erro:
client_socket.close()
print("Erro:", erro)
except Exception as erro:
print("Erro:", erro)
finally:
server.close()
Client
import socket
client = socket.socket()
try:
ip = "127.0.0.1"
port = 111
client.connect((ip, port))
while True:
print("Digite 1 para Cadastrar")
print("Digite 2 para Listar")
print("Digite 3 para Sair")
msg_send = input()
if msg_send == "1":
client.send(str.encode("1"))
print("Digite o Nome:")
nome = input()
print("Digite o E-mail:")
email = input()
print("Digite o Telefone:")
tel = input()
data_form = str.encode("{0} {1} {2}\n".format(nome, email, tel))
print("Nome: {0} E-mail: {1} Telefone: {2}".format(nome, email, tel))
print("======================")
client.send(data_form)
elif msg_send == "2":
client.send(str.encode("2"))
file_list = client.recv(5120)
print("======================")
print("Lista")
for line in bytes.decode(file_list).split("\n"):
field = line.split(" ")
if field[0]:
print("Nome: {0} | E-mail: {1} | Telefone: {2}".format(field[0],field[1], field[2]))
print("======================")
elif msg_send == "3":
client.send(str.encode("3"))
print(bytes.decode(client.recv(1024)))
break
except Exception as erro:
print("Erro:", erro)
finally:
client.close()
Qualquer coisa me manda uma msg, boa sorte.