Re: Receive data from socket stream



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
.



Relevant Pages

  • Re: Multiplicity, Change and MV
    ... as a String, for example. ... A lecturer teaches more than one course. ... As to your comment about loops, Mr Badour's comments and your question about ... different primary keys) the representation within the file structure is much ...
    (comp.databases.theory)
  • Re: Splitting a large string variable into lines <= 70 chars
    ... I kinda agree with you that perhaps the string search methods and functions like InStrRev and LastIndexOf will not be the fastest way. ... Wait till they grumble it's slow and then throw in a faster routine and your a hero again! ... All he'd done was reduce the number of iterations his code spent in the wait loops. ... Instead, do not modify the original string at all during the loop, ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Trouble Using System.Array.ForEach
    ... both a loop and an if-then, as well as some string manipulation. ... loops are very important and useful, but in this case I think I could do ... Nathan Sokalski ... I am trying to avoid) or the ForEach method. ...
    (microsoft.public.dotnet.languages.vb)
  • RE: VBA output to text editor
    ... just running empty loops took 2-3 ... RecA As String * 2 ... Sub BuildFile() ... Dim e As Integer, f As Integer, i As Long ...
    (microsoft.public.excel.programming)
  • Re: text compare takes very long...
    ... b1 = StrConv(String1, vbFromUnicode) ... In the earlier versions (where the loops in the main ... algorithm were equal to the product of the two string lengths) it would be ... loops in the new algorithm are much less than the product of the two string ...
    (microsoft.public.vb.general.discussion)