我在尝试将数据发送回服务器时遇到'TypeError:强制转换为Unicode:需要字符串或缓冲区,找到元组'。 这是我的代码:
(?<=\b|_)[^\W_]{5}(?:-[^\W_]{5}){4}(?=\b|_)
该程序应该向服务器发送UDP消息,然后获取单词列表作为响应,然后这应该以相反的顺序将列表发送回服务器。只要EOM为True,就应该这样做。
首先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_socket.sendto(data, (address, port))
,我不知道为什么。
答案 0 :(得分:2)
您正在
中覆盖address
data_recv, address = udp_socket.recvfrom(1024)
这样它就是一个元组。使用
data_recv, (address, port) = udp_socket.recvfrom(1024)