newbie udp socket question
Andrew Bennetts
andrew-pythonlist at puzzling.org
Sat May 10 22:49:24 EDT 2003
On Sun, May 11, 2003 at 02:13:25AM +0200, p@ wrote:
> Hi list,
>
> I have made the following UDP client:
>
> class UdpClientSocket:
> def __init__(self,address,port,request):
> sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> sock.sendto(str(request),address)
> response = sock.recv(port) #response here
> command = response[0]
> if command =='\x02':
> print 'server is still alive'
> if command =='\x04':
> print 'server tcp queue accepted'
> if command =='\x06':
> print 'Member address recieved'
> if command =='\x08':
> print 'cluster update redirected'
>
> sock.close()
>
> udpc = UdpClientSocket(('localhost',serverPort),clientPort,'\x01')
>
>
> The problem is if I don't get any response from the server it will block
> forever. So how do I implement a timeout for this?
> I have found a tcp-timeout-socket but none for udp...
Personally, I'd just use Twisted :)
Here's an untested example of your code implemented in Twisted, complete
with a 10 second timeout.
from twisted.internet.protocol import ConnectedDatagramProtocol
from twisted.internet import reactor
class MyUDPClient(ConnectedDatagramProtocol):
def __init__(self, request):
self.request = str(request)
def startProtocol(self):
self.transport.write(self.request)
def datagramReceived(self, data):
if command =='\x02':
print 'server is still alive'
if command =='\x04':
print 'server tcp queue accepted'
if command =='\x06':
print 'Member address received'
if command =='\x08':
print 'cluster update redirected'
self.transport.loseConnection()
reactor.stop()
reactor.connectUDP('localhost', serverPort, MyUDPClient('\x01'),
localport=clientPort)
reactor.callLater(10, reactor.stop) # 10 second timeout
reactor.run()
You could use non-blocking sockets and a select loop to achieve this
manually, but I find letting a library do all hard work for me much easier
:)
-Andrew.
More information about the Python-list
mailing list