On Feb 16, 6:18 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > ---------------------------------------------------------------- > 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. >
If you don't care about the address of the sender, e.g. you are not going to send anything back, is there an advantage to using recv()? Or, as a matter of course should you always use recvfrom() with udp sockets? > 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 Thanks -- http://mail.python.org/mailman/listinfo/python-list