2016-06-06 5 views
3

udp 서버와 클라이언트를 작성했습니다. 클라이언트는 서버에 간단한 udp 메시지를 보내면 서버가 응답합니다. 서버는 일부 응답 패킷을 임의로 삭제합니다. 내 클라이언트 측 코드에서 다음 줄을 작성했습니다.Python : 소켓 데이터 수신을위한 고정 대기 시간

for i in range(0,10): 
    sequence_number = i 
    start = time.time() 
    clientSocket.sendto("Ping " + str(i) + " " + str(start), server) 
    # Receive the client packet along with the address it is coming from 
    message, address = clientSocket.recvfrom(1024) 
    end = time.time() 
    if message != '': 
    print message 
    rtt = end - start 
    print "RTT = " + str(rtt) 

서버가 응답을 중단하면 다음 행이 계속 붙습니다.

message, address = clientSocket.recvfrom(1024) 

나는 여기에 시간 제한 방법을 시도 : Socket recv - limited wait time
하지만 제한 시간은 전체 클라이언트 프로그램을 중단합니다. 클라이언트가 5 초 동안 기다린 다음 마지막 응답이 수신되지 않으면 (서버에 의해 삭제 된 경우) 다음 패킷을 계속 보내길 원할뿐입니다. 클라이언트에서 대기 시간을 어떻게 설정할 수 있습니까?

답변

4

settimeout()와의 링크가 맞았습니다. 제한 시간이 초과되면 Exception을 발생시킵니다.

소켓 작동을 차단할 때 시간 초과를 설정하십시오. value 인수는 초를 나타내는 음수가 아닌 부동 소수점 숫자 또는 None이 될 수 있습니다. 값이 0이 아닌 경우 작업이 완료되기 전에 제한 시간 값이 경과하면 후속 소켓 작업에서 시간 초과 예외가 발생합니다. 0이 주어지면, 소켓은 비 차단 모드에 놓입니다. None을 지정하면 소켓은 모드로 차단됩니다.

코드가 try 블록에 있어야 예외가 프로그램을 중단하지 않아야합니다.

import socket.timeout as TimeoutException 
# set timeout 5 second 
clientsocket.settimeout(5) 
for i in range(0,10): 
    sequence_number = i 
    start = time.time() 
    clientSocket.sendto("Ping " + str(i) + " " + str(start), server) 
    # Receive the client packet along with the address it is coming from 
    try: 
    message, address = clientSocket.recvfrom(1024) 
    except TimeoutException: 
    print("Timeout!!! Try again...") 
    continue 
    end = time.time() 
    if message != '': 
    print message 
    rtt = end - start 
    print "RTT = " + str(rtt)