sockets -- basic udp client

rluse1 at gmail.com rluse1 at gmail.com
Sat Feb 16 08:18:10 EST 2008


----------------------------------------------------------------
Here is the example above converted to a more straightforward udp
client that isolates the part I am asking about:

import socket, sys

host =  'localhost'  #sys.argv[1]
port = 3300
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

data = 'hello world'
num_sent = 0
while num_sent < len(data):
    num_sent += s.sendto(data, (host, port))

print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
while 1:
    buf = s.recv(2048)

    #Will the following if statement do anything?
    if not len(buf):
        break

    print "Received from server: %s" % buf
--------------------------------------------------------------

There is still a problem with your script.

buf = s.recv(2048)  should be changed to

buf, addr = s.recvfrom(2048)  or
buf = s.recvfrom(2048)[0]

or something like that since recvfrom returns a pair.

But, for the specific case that you have asked about, since the
default for timeout is no timeout, or block forever, your question:

#Will the following if statement do anything?
    if not len(buf):
        break

The answer is that you are right, it will do nothing.  But, if you set
a time out on the socket, and you receive no data and the timeout
expires, checking for the length of zero and a break is one way to
jump out of the loop if you need to.

For example:

import socket, sys

host =  'localhost'  #sys.argv[1]
port = 3300
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.settimeout(1.0)
buf = ''

data = 'hello world'
num_sent = 0

while num_sent < len(data):
    num_sent += s.sendto(data, (host, port))

print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
while True:

    try:
        buf, addr = s.recvfrom(2048)
    except:
        pass

    #Will the following if statement do anything?
    # In this case it will cause the script to jump out of the loop
    # if it receives no data for a second.
    if not len(buf):
        break

    print "Received from server: %s" % buf


For getservbyname and its complement, getservbyport, they are talking
about well known protocols like http, ftp, chargen, etc.  The
following script is a very simple example:

import socket

print socket.getservbyname('http')

print socket.getservbyname('ftp')
print socket.getservbyname('time')


print socket.getservbyport(80)


 - Bob



More information about the Python-list mailing list