Search code examples
pythonencodingutf-8udpclient

Encoding problem when printing message in UDP client-server using Python


I am trying to create a UDP client-server from a TCP one. I ran into an issue with encoding and printing my receiving message from the server to the client. It works the way I have it on TCP but doesn't seem to work on UDP and I am not sure on what else I have to encode?

Here is the error I am getting:

File "/Users/PycharmProjects/UDPProject/client.py", line 29, in <module>
    print("received %s" % command)
TypeError: not all arguments converted during string formatting

And here is my client code with some code cut out.

while True:

    message = input("Please enter a command:\n")  # ask user to input message
    if message == 'quit':
        break
    if len(message) == 0:
        print("Please enter something")
        message = input("Please enter a command:\n")
    print("Sending %s" % message)
    sock.sendto((message.encode("utf-8")), address)  # send message
    command = str(sock.recvfrom(BUFFER_SIZE), "utf-8")
    print("received %s" % command)

print("closing connection with server")
sock.close()

It is happening when the socket is trying to receive from the buffer size in utf-8 format and when I try to print it.

EDIT: I fixed the error, it was just typo as outlined by lenz but now it gives me this error

command = str(sock.recvfrom(BUFFER_SIZE), "utf-8")
TypeError: decoding to str: need a bytes-like object, tuple found

I am not sure why???


Solution

  • socket.recvfrom returns a tuple of pair (bytes, address) in UDP so I had to decode the first item of bytes. This is how I did it.

    command = str(sock.recvfrom(BUFFER_SIZE)[0], "utf-8"). The [0] grabs the first item in the tuple of BUFFER_SIZE