J. Rautava
J. Rautava

Reputation: 114

Why I'm getting TypeError

I'm getting 'TypeError: coercing to Unicode: need string or buffer, tuple found' when trying to send data back to server. Here is my code:

def send_and_receive_udp(address, port, id_token):
    # Create UDP socket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Contents of message
    message = 'Hello from %s\r\n' %id_token
    ack = True
    eom = False
    dataRemaining = 0
    length = len(message)
    data = struct.pack('!8s??HH64s', id_token, ack, eom, dataRemaining, length, message)


    # Send given message to given address and port using the socket
    udp_socket.sendto(data, (address, port))


    while(True):
    # Send given message to given address and port using the socket
        # Receive data from socket
        data_recv, address = udp_socket.recvfrom(1024)

        id_token, ack, eom, dataRemaining, length, message = struct.unpack('!8s??HH64s', data_recv)
        print message
        # Last EOM is True, otherwise False
        if(eom == True):
            # Break loop
            print 'Lopetetaan'
            break
        words = []
        chars = []
        # Append list from message one character at time
        for i in range(length):
            chars.append(message[i])
        # Join words back to one string
        word = ''.join(chars)
        # Make a array where every word is one member of array
        words = word.split(' ')
        words.reverse()
        # Make a new string from array
        send_data = ' '.join(words)+'\r\n'

        data = struct.pack('!8s??HH64s', id_token, ack, eom, dataRemaining, length, send_data)

        udp_socket.sendto(data, (address, port))
    # close the socket
    udp_socket.close()
    return

This program is supposed to send UDP-message to server, then get list of words as response and then this should send the list in reversed order back to server. This is supposed to go as long as EOM is True.

First udp_socket.sendto(data, (address, port)) works just as I want. The last one creates this TypeError and I have no idea why.

Upvotes: 0

Views: 98

Answers (1)

Daniel
Daniel

Reputation: 42768

You are overwriting address in

data_recv, address = udp_socket.recvfrom(1024)

so that it is a tuple. Use

data_recv, (address, port) = udp_socket.recvfrom(1024)

Upvotes: 2

Related Questions