简体   繁体   English

如何检查python socket recvfrom()数据

[英]How to check the python socket recvfrom() data

I am working on socket programming in python. 我正在使用python进行套接字编程。 Using ESP python i have created a socket to server and sending a request (in API packet format, according to server code it will respond). 我使用ESP python创建了一个到服务器的套接字并发送请求(以API数据包格式,将根据服务器代码响应)。 In receiving socket, i need to check the data(if data is received, it need continue to next operation. If not, i need to send request once again). 在接收套接字中,我需要检查数据(如果接收到数据,则需要继续进行下一个操作。否则,我需要再次发送请求)。 sending is okay. 可以发送。 In receiving socket, if it is not receiving data, it is not going to next instruction.. please help me out. 在接收套接字时,如果它不接收数据,则不会进行下一条指令..请帮助我。

code: 码:

try:

    s = socket(AF_INET, SOCK_DGRAM)
    print "socket created"

except socket.error:

    print "failed to create socket"
    sys.exit()

sending data: 发送数据:

s.sendto("packet of data", 0, (HOST,PORT))

In receiving: 在接收中:

recvpack, payload=s.recvfrom(1024)

if not recvpack:

    s.sendto("packet of data", 0, (HOST,PORT))

elif(recvpack[]="packet of data"):

    pass # continue to next operations..

In the above receiving statement, if recvfrom() in not getting anydata, how to check recvpack and get back to next operations.. If socket.settimeout() or socket.setblocking() is the solution, how to use these.. 在上面的接收语句中,如果recvfrom()未获取任何数据,则如何检查recvpack并返回到下一个操作。如果解决方案为socket.settimeout()socket.setblocking() ,则如何使用它们。

If you don't mind a blocking call, I usually use settimeout to wait for a message. 如果您不介意阻止呼叫,我通常使用settimeout等待消息。 settimeout will raise an exception if it doesn't receive a message in time. 如果settimeout没有及时收到消息,它将引发异常。

So basically you could do something like this: 因此,基本上您可以执行以下操作:

s.settimeout(1)
try:
    recvpack, payload = s.recvfrom(1024)
except error:
    recvpack = None
if recvpack is not None:
    ...

Source : https://docs.python.org/2/library/socket.html#socket.socket.settimeout 来源: https : //docs.python.org/2/library/socket.html#socket.socket.settimeout

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

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