How to end TCP socket data while using readline()?

MRAB python at mrabarnett.plus.com
Fri Feb 26 14:45:58 EST 2010


Arjun Chennu wrote:
> No need to flush because you're writing to a file and it'll be flushed
> 
>     anyway when you close it.
> 
> 
> True. I had introduced those flush lines while I was trying to 
> troubleshoot this annoying situation. :-)
> 
>     You've closed the file view, but the underlying socket is still open.
> 
> 
>     The server will see EOF only when the socket is closed by the client,
>     and closing the file view doesn't close the socket itself.
> 
> 
> That's what I intended to do. Keep the socket open, but close the file 
> object so that the direction of transfer can be reversed and a "done" 
> message can be sent to the client.
> 
> TCP is meant to facilitate two-directional transfer innit? So how do I 
> do that while using file objects? If i have to close the socket to do 
> that, it seems a bit wasteful in terms of network 'transactions'
> 
> Thanks for your reply. I've already confirmed that closing the socket 
> does indeed move the program ahead --- but I'd like to now make 
> two-directional comm. possible.
> 
Here's a trick borrowed from the POP3 format (used for email).

Server code:
     ...
     cf = conn.makefile('r', 0)    # file like obj for socket
     lf = open('ccs.txt', 'w')
     for line in cf:
         if line == '.end\n':
             break
         if line.startswith('..'):
             line = line[1 : ]
         lf.write(line)
         sys.stdout.write(line)
         print len(line)
     lf.close()
     cf.close()
     ...


Client code:
     ...
     cf = s.makefile('w', 0)
     for line in sfp.readlines():
         if line.startswith('.'):
             cf.write('.')
         cf.write(line)
         print len(line)
     cr.write('.end\n')
     print 'close'
     cf.close()
     ...



More information about the Python-list mailing list