Receive data from socket stream
s0suk3 at gmail.com
s0suk3 at gmail.com
Mon Apr 28 18:29:33 EDT 2008
On Apr 28, 4:42 am, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Nick Craig-Wood <n... at craig-wood.com> writes:
> > What you are missing is that if the recv ever returns no bytes at all
> > then the other end has closed the connection. So something like this
> > is the correct thing to write :-
>
> > data = ""
> > while True:
> > new = client.recv(256)
> > if not new:
> > break
> > data += new
>
> This is a good case for the iter() function:
>
> buf = cStringIO.StringIO()
> for new in iter(partial(client.recv, 256), ''):
> buf.write(new)
> data = buf.getvalue()
>
> Note that appending to a string is almost never a good idea, since it
> can result in quadratic allocation.
A question regarding cStringIO.StringIO(): is there a way to do get
getvalue() to return all the bytes after the current file position
(not before)? For example
buf = cStringIO.StringIO()
buf.write("foo bar")
buf.seek(3)
buf.getvalue(True) # the True argument means
# to return the bytes up
# to the current file position
That returns 'foo'. Is there a way to get it to return ' bar'?
More information about the Python-list
mailing list