sockets -- basic udp client

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Feb 15 20:48:55 EST 2008


En Fri, 15 Feb 2008 20:24:19 -0200, 7stud <bbxx789_05ss at yahoo.com>  
escribió:

> My question pertains to this example:
>
> #!/usr/bin/env python
>
> import socket, sys, time
>
> host = sys.argv[1]
> textport = sys.argv[2]
>
> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> try:
>     port = int(textport)
> except ValueError:
>     # That didn't work.  Look it up instread.
>     port = socket.getservbyname(textport, 'udp')
>
> s.connect((host, port))
> print "Enter data to transmit: "
> data = sys.stdin.readline().strip()
> s.sendall(data)
> s.shutdown(1)
> print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
> while 1:
>     buf = s.recv(2048)
>     if not len(buf):
>         break
>     print "Received: %s" % buf
>
>
> As far as I can tell, the if statement:
>
> if not len(buf):
>    break
>
> does nothing.  Either recv() is going to read some data or it's going
> to block.   My understanding is that udp sockets do not have a
> connection, so the server can't close the connection--hich would cause
> a blank string to be sent to the client.
>
> So, as far as I can tell, the only way that code would make sense is
> if the server were programmed to send a blank string to the client
> after it sent data to the client.  Is that correct?

That example is plain wrong; looks like some TCP code but with SOCK_STREAM  
blindy replaced with SOCK_DGRAM. connect, sendall and recv are not used  
for UDP; sendto and recvfrom are used instead. There are some examples in  
the Demo python directory.

-- 
Gabriel Genellina




More information about the Python-list mailing list