Problems with print in python socket

Asked

Viewed 32 times

-1

I’m already hours away trying to solve this error, well... in the python socket I made a program in which the client sends his name and the program picks up the IP and the date and time that he sent and writes this information in a file. txt

But I’m having trouble with the customer information prints

This is the server code:

#SERVIDOR
from socket import *
from time import *

sala = socket(AF_INET, SOCK_STREAM)
sala.bind(('', 58117))
sala.listen()
print('Aguardando Clientes...\n')

while True:
   con, adr = sala.accept()
   
   client_nome = con.recv(1024).decode()
   IP = con.recv(1024).decode()
   data = con.recv(1024).decode()
   hora = con.recv(1024).decode()
   print(f'Nome: {client_nome}')
   print(f'IP: {IP}')
   print(f'Data: {data} | Hora: {hora}')

   with open('/storage/emulated/0/python/pessoas.txt', 'a') as ip:
      ip.write(f'\nPessoa: {client_nome}\nIP: {IP}\n{data}\n')

This is the client’s:

#CLIENTE
from time import *
from socket import *
from requests import *

dh = localtime()

client = socket(AF_INET, SOCK_STREAM)
client.connect(('', 58117))

client_nome = str(input('Apelido: '))
IP = get('https://api.ipify.org').text

data = str(f'{dh[2]}/{dh[1]}/{dh[0]}')
hora = str(f'{dh[3]}:{dh[4]}')

client.send(client_nome.encode())
client.send(IP.encode())
client.send(data.encode())
client.send(hora.encode())

This is the result with the buged prints:

Aguardando Clientes..


Nome: TESTE PY
IP: THON
Data: 177.107.10 | Hora: 7.24

The name part invaded the ip area, the ip was in the date and time part, and the date and time were gone kkk I really don’t know what’s wrong, I’m new to the socket, so please someone help me get this "Bug"

  • Try to add on this line client.send(client_nome.encode()) one \n. This should cause the socket.send to flush...

  • Allah, in all they send.

1 answer

0

If you guarantee that the message is less than 1024, this will serve

Server

#SERVIDOR
from socket import *
from time import *

sala = socket(AF_INET, SOCK_STREAM)
sala.bind(('', 58117))
sala.listen()
print('Aguardando Clientes...\n')

while True:
   con, adr = sala.accept()

   dados = con.recv(1024).decode()

   print(dados)

   client_nome, IP, data, hora = dados.split("|")

   print(f'Nome: {client_nome}')
   print(f'IP: {IP}')
   print(f'Data: {data} | Hora: {hora}')

   with open('./pessoas.txt', 'a') as ip:
      ip.write(f'\nPessoa: {client_nome}\nIP: {IP}\n{data}\n')

Client

#CLIENTE
from time import *
from socket import *
from requests import *

dh = localtime()

client = socket(AF_INET, SOCK_STREAM)
client.connect(('', 58117))

client_nome = str(input('Apelido: '))
IP = get('https://api.ipify.org').text

data = str(f'{dh[2]}/{dh[1]}/{dh[0]}')
hora = str(f'{dh[3]}:{dh[4]}')

client.send((f'{client_nome}|{IP}|{data}|{hora}').encode())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.