Timeout on a UDP Socket
Josh Smith
josh+news at nextyme.net
Sun Mar 21 10:38:41 EST 2004
In article <a1ff320f.0403202029.55bc8d5f at posting.google.com>, w wrote:
> I'm having problems with this program hanging on the revc(buf). I was
> trying to figure out a way to allow the socket to timeout. I'm have
> tried making the socket non-blocking but had on luck. Being very new
> to Python, could there be a better way to accomplish this task. The
> program works very well, but on occassion is will not receive the data
> from the server and hang.
You could use a sigalarm (assuming your OS supports that).
For an example from the python docs:
http://www.python.org/doc/current/lib/node304.html
I've also added some example code to your client example demonstrating this (if
you'll excuse the intrusion into your code :) )
-jbs
# Client program
import os.path,signal
from socket import *
from time import *
# Set the socket parameters
#host = "localhost"
host = "10.0.0.20"
port = 21567
buf = 1024
addr = (host,port)
def handler(signum,frame):
"""This is a handler function called when a SIGALRM is received,
it simply raises a string exception"""
raise "SocketTimeOut"
# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
# Send messages
while(1):
if not os.path.exists( "user1.inp" ) :
sleep( 2 )
else:
print "opening....."
print "reading....."
in_file = open("user1.inp", "r")
data = in_file.readline()
#print in_line
in_file.close()
if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'.....<done>"
if os.path.exists( "user1.inp" ) :
os.remove( "user1.inp" )
print "Waiting for Response..."
# Receive messages
try:
# setup signal handler
signal.signal(signal.SIGALRM,handler)
# 10 seconds is the limit
signal.alarm(10)
data = UDPSock.recv(buf)
# shutdown the alarm
signal.alarm(0)
print "\nReceived message '", data,"'"
#output result message from server
f=open( "user1.out", "w" )
f.write( data )
f.close()
except "SocketTimeOut":
f=open("user1.out","w")
f.write("Timed out on receive from "+host+", got no data\n")
f.close()
# Close socket
UDPSock.close()
More information about the Python-list
mailing list