Re: Python recv loop

Discussion in 'Python' started by MRAB, Feb 11, 2013.

  1. MRAB

    MRAB Guest

    On 2013-02-11 00:48, Ihsan Junaidi Ibrahim wrote:
    > Hi,
    >
    > I'm implementing a python client connecting to a C-backend server and am currently stuck to as to how to proceed with receiving variable-length byte stream coming in from the server.
    >
    > I have coded the first 4 bytes (in hexadecimal) of message coming in from the server to specify the length of the message payload i.e. 0xad{...}
    >
    > I've managed to receive and translate the message length until I reach my second recv which I readjusted the buffer size to include the new message length.
    >
    > However that failed and recv received 0 bytes. I implemented the same algorithm on the server side using C and it work so appreciate if you can help me on this.
    >
    > # receive message length
    > print 'receiving data'
    > mlen = sock.recv(4)
    > try:
    > nbuf = int(mlen, 16)
    > except ValueError as e:
    > print 'invalid length type'
    > return -1
    >
    > while True:
    > buf = sock.recv(nbuf)
    >
    > if not buf:
    > break
    >
    > slen = len(buf)
    > str = "{0} bytes received: {1}".format(slen, buf)
    > print str
    >

    You should keep reading until you get all need or the connection is
    closed:

    buf = b''
    while len(buf) < nbuf:
    chunk = sock.recv(nbuf - len(buf))

    if not chunk:
    break

    buf += chunk
    MRAB, Feb 11, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. deepak nayak
    Replies:
    3
    Views:
    423
    =?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=
    Oct 25, 2007
  2. Ihsan Junaidi Ibrahim

    Python recv loop

    Ihsan Junaidi Ibrahim, Feb 11, 2013, in forum: Python
    Replies:
    7
    Views:
    159
  3. Dave Angel

    Re: Python recv loop

    Dave Angel, Feb 11, 2013, in forum: Python
    Replies:
    0
    Views:
    123
    Dave Angel
    Feb 11, 2013
  4. Ihsan Junaidi Ibrahim

    Re: Python recv loop

    Ihsan Junaidi Ibrahim, Feb 11, 2013, in forum: Python
    Replies:
    0
    Views:
    110
    Ihsan Junaidi Ibrahim
    Feb 11, 2013
  5. Isaac Won
    Replies:
    9
    Views:
    372
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page