为什么我越来越TypeError

问题描述:

当我试图将数据发送回服务器时,出现'TypeError:强制为Unicode:需要字符串或缓冲区,发现元组'。 这里是我的代码:为什么我越来越TypeError

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,我不知道为什么。

+0

它是从底部开始的第4行。 –

您在

data_recv, address = udp_socket.recvfrom(1024) 

覆盖address所以它是一个元组。使用

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

这样做!谢谢! –