Re: Receive data from socket stream
- From: Nick Craig-Wood <nick@xxxxxxxxxxxxxx>
- Date: Mon, 28 Apr 2008 08:30:03 -0500
Hrvoje Niksic <hniksic@xxxxxxxxxx> wrote:
Nick Craig-Wood <nick@xxxxxxxxxxxxxx> 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.
My aim was clear exposition rather than the ultimate performance!
Anyway str += was optimised in python 2.4 or 2.5 (forget which) wasn't
it? I'm not convinced it will be any worse performing than
cStringIO.StringIO.write() which effectively appends to a string in
exactly the same way.
This test agrees with me!
$ python -m timeit -s 's = ""' 'for i in xrange(100000): s+="x"'
10 loops, best of 3: 23.8 msec per loop
$ python -m timeit -s 'from cStringIO import StringIO; s=StringIO()' 'for i in xrange(100000): s.write("x")'
10 loops, best of 3: 56 msec per loop
--
Nick Craig-Wood <nick@xxxxxxxxxxxxxx> -- http://www.craig-wood.com/nick
.
- Follow-Ups:
- Re: Receive data from socket stream
- From: Hrvoje Niksic
- Re: Receive data from socket stream
- From: Jean-Paul Calderone
- Re: Receive data from socket stream
- References:
- Receive data from socket stream
- From: s0suk3
- Re: Receive data from socket stream
- From: Nick Craig-Wood
- Re: Receive data from socket stream
- From: Hrvoje Niksic
- Receive data from socket stream
- Prev by Date: Re: function that accepts any amount of arguments?
- Next by Date: Cookie Confusion - How to Set a Cookie
- Previous by thread: Re: Receive data from socket stream
- Next by thread: Re: Receive data from socket stream
- Index(es):
Relevant Pages
|