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

Arjun arjun.chennu at gmail.com
Fri Feb 26 13:39:08 EST 2010


Hi, I have a small script that runs a TCP server. A client connects to
this server and transmits a stored file line-by-line, and then waits
for a confirmation "done". However, when I run them the first loop
never really ends -- as the TCP server keeps expecting more data. I am
using a file-like-object, and so somehow I have to communicate to the
server that it is the end-of-file.

here is some server code
<snip>
            sock1.bind(('', port))
            print "Listening at port: ", port
            sock1.listen(1)      # listening socket
            (conn, addr) = sock1.accept()    # connected socket
            print 'Client (localhost) port: ', addr[1]

            cf = conn.makefile('r',0)    # file like obj for socket

            lf = open('ccs.txt','w')
            for line in cf:
                lf.write(line)
                lf.flush()
                sys.stdout.write(line)
                print len(line)

            lf.close()      (*here*)
            cf.close()
            cf = conn.makefile('w',0)
            print len(line)
            print 'sendin'
            stat = 'done'
            cf.write(stat)
            print stat
            print 'sent'
            cf.close()
            print 'script done & connection closed'
</snip>

The client is sending the lines through this code:
<snip>
        s.connect((host,port))
        sfp = open("dcs.txt")
       # script = sfp.readlines()
        stat = 'still'
        cf = s.makefile('w',0)
        for line in sfp.readlines():
            cf.write(line)
            print len(line)
        print 'close'
        cf.flush()
        cf.close()
        sfp.close()

        cf = s.makefile('r',0)
        print stat, 'waiting'
        stat = cf.readline()
        print stat, 'waiting'  # this should become "done waiting"
        cf.close()
        s.close()
</snip>

So what I am wondering is:

1. Using a file-like object means that the socket becomes uni-
directional, until the mode of the file object is changed from 'r' to
'w' (or vice versa). This seems inefficient, and rather unPythonesque.
Can somebody tell me if there is a more elegant way of receiving all
the lines from the client, and then sending a "done" message to the
client?

2.  Where I have marked (*here*) in the server code, is where the
execution seems to stay waiting... apparently for more input from the
client. But then when I force-terminate the client script, the
execution continues on the server-side!! So then it sends the "done"
status to a (already dead) client, and then exits. How do I get the
server to know when the EOF has been reached while using FLOs?

Input on this will be much appreciated, because the documentation for
readlines() didn't help me with this.

Cheers,
A



More information about the Python-list mailing list