为什么我要打电话

2024-10-01 22:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在尝试将数据发送回服务器时,我得到“TypeError:强制到Unicode:需要字符串或缓冲区,找到元组”。 这是我的密码:

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

这个程序应该向服务器发送UDP消息,然后得到单词列表作为响应,然后按相反的顺序将列表发送回服务器。只要EOM是真的就应该这样。你知道吗

首先udp_socket.sendto(data, (address, port))按我的意愿工作。最后一个创建了这个TypeError,我不知道为什么。你知道吗


Tags: fromtokenidtruemessagedataportaddress

热门问题