sockets -- basic udp client

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Feb 16 14:32:48 CET 2008


En Sat, 16 Feb 2008 05:56:39 -0200, 7stud <bbxx789_05ss at yahoo.com>  
escribi�:

>> > 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--which 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?

Your analysis looks correct to me. If it were using TCP, an empty string  
signals that the other side has closed the connection, but being UDP it  
cannot happen (unless the server explicitely sends an empty string, as you  
said).

>> 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.
>
> Yes, I agree it's a poor example--it's from 'Foundations of Python
> Network Programming'--but it does 'work'.  It also doesn't appear to
> be a tcp client that was converted too directly into a udp client
> because the previously presented tcp examples are different.

Ok, you *can* use those functions with datagrams too, but it's confusing  
(at least for the very first UDP example!)

> Another question I have pertains to the docs here:
>
> getservbyname(servicename[, protocolname])
> Translate an Internet service name and protocol name to a port number
> for that service. The optional protocol name, if given, should be
> 'tcp' or 'udp', otherwise any protocol will match.
>
> What does a 'servicename' look like?

py> import socket
py> socket.getservbyname("http")
80
py> socket.getservbyname("smtp")
25

On Linux the mapping ports<->services is in /etc/services; on Windows see  
%windir%\system32\drivers\etc\services

-- 
Gabriel Genellina




More information about the Python-list mailing list