简体   繁体   English

socket.recvfrom函数返回一个元组(python)

[英]socket.recvfrom function returning a tuple (python)

I'm a python noobie and I must create a Truco (brazillian game, if you don't know) game that connects 4 machines. 我是python noobie,我必须创建一个可连接4台计算机的Truco(巴西游戏,如果您不知道的话)游戏。 I'm doing it with classes, using pickles to transfer it to a socket. 我正在使用类,使用泡菜将其传输到套接字。 According to what I could find online, this should work, but my recv is a tuple, and I can't use loads from a tuple. 根据我在网上可以找到的信息,这应该可以工作,但是我的recv是一个元组,并且我不能使用元组中的负载。 I've tried to convert it to a list, and then to a string, but nothing works! 我试图将其转换为列表,然后转换为字符串,但是没有任何效果!

def recv(self, machine):
    PORT = 5054
    HOST = ''
    orig = (socket.gethostbyname(HOST), PORT)
    machine._socketrcv.bind(orig)
    recv = machine._socketrcv.recvfrom(1024)
    return pickle.loads(recv)

And here is my send method: 这是我的发送方法:

def sent(self, m, machine):
    PORT = 5054
    dest = (machine._host, PORT)
    self._socketsnd.sendto(m._dados,dest)

Where m._dados is self.dados = pickle.dumps(dados, 2) 其中m._dados是self.dados = pickle.dumps(dados,2)

Can anyone help? 有人可以帮忙吗?

You probably want to read through socket and then do something like recv = machine._socketrcv.recvfrom(1024)[0] 您可能想通读套接字 ,然后执行诸如recv = machine._socketrcv.recvfrom(1024)[0]

socket.recvfrom(bufsize[, flags])

Receive data from the socket. 从套接字接收数据。 The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data. 返回值是一对(字符串,地址),其中字符串是代表接收到的数据的字符串,而地址是发送数据的套接字的地址。 See the Unix manual page recv(2) for the meaning of the optional argument flags; 有关可选参数标志的含义,请参见Unix手册页recv(2)。 it defaults to zero. 它默认为零。 (The format of address depends on the address family — see above.) (地址格式取决于地址系列-参见上文。)

recvfrom returns a tuple with the data and the address (more info can be found in the socket documentation ). recvfrom返回带有数据和地址的元组(更多信息可以在套接字文档中找到)。 Unlike some other languages Python lets you put a tuple on the left hand side of an assignment, so if you do something like this: 与某些其他语言不同,Python使您可以在任务的左侧放置一个元组,因此,如果执行以下操作:

data, (address, port) = machine._socketrcv.recvfrom(1024)

you will get access to all the information you need in separate named variables. 您将可以在单独的命名变量中访问所需的所有信息。 In your case you just need the data: 就您而言,您只需要数据:

pickle.loads(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM