I can not send more than one message because the client hangs up

0

I do not understand why after sending a message I can not send any more messages to my server from my client

#servidor
import socket

host = "127.0.0.1"
port = 6666

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("socket bind complete")
sock.listen(1)
print ("socket now listening")

while 1:
    conn, addr = sock.accept()
    datos = conn.recv(4096)
    print(datos.decode('utf-8'))

    conn.send("hello".encode('UTF-8'))

the client can connect to the server, the message from the server reaches the client only after sending the first message, when sending a second message from the client it is not possible

#cliente
import socket

host = "127.0.0.1"
port = 6666

sock = socket.socket()

sock.connect((host, port))

while True:


  message = input("envia un mensaje")
  sock.send(message.encode('utf-8'))


  datos = sock.recv(4096)
  print (datos.decode('utf-8'))

  if message == "quit":
    break
    print("bye")
    sock.close()
    
asked by steven 13.04.2017 в 14:27
source

1 answer

0

You need an infinite cycle inside the while that is in charge of looking for clients so that once connected one is in charge of receiving the data. The welcome message you send just connect the client and before starting the cycle to capture the data sent by the client.

In the client you must capture this message after the connection request to the server and before starting the cycle to read the data with input and send them:

Example of client and server with welcome message:

#cliente
import socket

host = "127.0.0.1"
port = 6666

sock = socket.socket()
sock.connect((host, port))

#Aquí esperamos recibir el mensaje de bienvenida del servidor. 
data = sock.recv(1024)
print(data.decode('UTF-8'))

while True:
    message = input("Envia un mensaje:")
    sock.send(message.encode('utf-8'))
    if message == "quit":
        break

print("bye")
sock.close()

.

#servidor
import socket

host = "127.0.0.1"
port = 6666
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket Created")
sock.bind((host, port))
print ("socket bind complete")

sock.listen(1)

while True:
    conn, addr = sock.accept() 
    try:
        print('Conexión con {}.'.format(addr))
        conn.send("Server: Hello client".encode('UTF-8'))
        while True:
            datos = conn.recv(1024)
            if datos:
                print('Recibido: {}'.format(datos.decode('UTF-8')))
            else:
                print('No más datos desde {}.'.format(addr))
                break     
    finally:
        conn.close()
    
answered by 13.04.2017 в 15:49