How to end TCP socket data while using readline()?
arjun.chennu at gmail.com
Fri Feb 26 19:39:08 CET 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
print "Listening at port: ", port
sock1.listen(1) # listening socket
(conn, addr) = sock1.accept() # connected socket
print 'Client (localhost) port: ', addr
cf = conn.makefile('r',0) # file like obj for socket
lf = open('ccs.txt','w')
for line in cf:
cf = conn.makefile('w',0)
stat = 'done'
print 'script done & connection closed'
The client is sending the lines through this code:
sfp = open("dcs.txt")
# script = sfp.readlines()
stat = 'still'
cf = s.makefile('w',0)
for line in sfp.readlines():
cf = s.makefile('r',0)
print stat, 'waiting'
stat = cf.readline()
print stat, 'waiting' # this should become "done waiting"
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
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.
More information about the Python-list