Re: strnge pb with sockets

Guido.van.Rossum@cwi.nl
Fri, 24 Feb 1995 15:43:05 +0100

Olivier Marce writes:

> I've tried the following *in interactive mode* :
> >>> from socket import *
> >>> adresse='user@machine1'
> >>> machine='machine5'
> >>> import string
> >>> adr=string.splitfields(adresse,'@')
> >>> canal=socket(AF_INET, SOCK_STREAM)
> >>> canal.connect(adr[1], 25)
> >>> data='helo '+machine+'\nvrfy '+adr[0]+'\n'
> >>> canal.send(data)
> 21
> >>> d=canal.recv(1024)
> >>> print (d), len(d)
> 220 machine1.ens-cachan.fr Sendmail 4.1/88/01/19 3.0 ready at Wed, 22 Feb 95 11:41:41 +0100
> 250 machine1.ens-cachan.fr Hello lifac5 (lifac6), pleased to meet you
> 250 Olivier MARCE <user>
> 185
> >>>
>
> All is ok.
>
> But if I put the *same* lines in a file and I execute it :
>
> machine6% python titi
> 220 machine1.ens-cachan.fr Sendmail 4.1/88/01/19 3.0 ready at Wed, 22 Feb 95 12:14:02 +0100
> 91

And in a follow-up:

> Juste make a 'canal.makefile('r')'
> and 'canal.shutdown(1)'.
> then you can use 'f.readline()'
>
> But :
> 1 - I don't understand the difference between the interactive
> mode and the program mode

You ran into a timing problem. Unlike f.readline(), which insists on
reading up to a '\n' character (or EOF), s.recv() reads as little or
as much as happens to be available at the time it is called -- unless
nothing is available, in which case it blocks until at least
*something* arrives, and then returns that.

Interactively, unless you can type very fast, you give the server and
the network enough time to send the whole reply. But in a program,
you are calling recv() almost immediately after sending, so you only
get the first packet of data that arrives.

> 3 - looking at httplib.py, Guido use
> while 1:
> line = f.readline()
> if not line:
> break
>
> Using this I have one more error message :
>
> 421 machine1.ens-cachan.fr Lost input channel to machine6

(What happened to question 2? :-)

I think you shouldn't have done the canal.shutdown(1) -- it has
nothing to do with solving the problem you have, but closes the write
end of the socket (which supplies the input for the server). The
server responds to this with this error.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>