send a message to the client from the server with the use of sockets in python 3.6

2

Hi I do not understand why my server reasoned

#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("esto es un mensaje de bienvenida".encode('UTF-8'))

the message does not reach my client

#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'))

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


  if message == "quit":
    break
    print("bye")
    sock.close()

output:

traceback (most recent call last) file "client.py", line 16 in  conn, addr = sock.accept ()

file "f: \ python \ lib \ socket.py", line 205 in accept fd, addr = self.accept ()

OSerror = [winerror 10022] an invalid argument has been provided

    
asked by steven 12.04.2017 в 23:55
source

1 answer

1

Through the socket you must send bytes not strings of text (str). To send text you simply code it in the client and then decode it in the server using the same encoding (UTF-8, Latin-1, etc).

To do this you should only use the str.encode() method on the server as you do on the client:

conn.send("esto es un mensaje de bienvenida".encode('UTF-8'))

To read the data you must do the opposite process with the bytes that you receive both on the server and client:

respuesta.decode('UTF-8')

The second error occurs on the client side because the server does not exist due to the previous error.

To be able to read the incoming data you need to use conn.recv(buffer_size) where buffer_size is the size of the buffer, it is the number of bytes that can be received each time. An example of a server for your client that prints what arrives would be:

#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))
        while True:
            datos = conn.recv(4096)
            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 в 00:05