Client for server doing dispatcher_with_send

Discussion in 'Python' started by Victor Norman, Oct 8, 2004.

  1. Hi all,

    I have a server that uses the asyncore stuff with dispatcher_with_send in
    order to send a bunch of pickled bytes to a client. The length of the
    message is generally about 3000 bytes.

    My problem is that I don't know how to write the client elegantly. I'm not
    using asyncore or anything for the client -- just the socket module.

    Currently, my code is working, but is inelegant, I think. here it is:

    data = ""
    newData = ""
    while True:
    newData = sock.recv(8192)
    data += newData
    if len(newData) < 512:
    break
    sock.close()

    This works because the dispatcher_with_send() sends packets with 512 bytes
    in them, unless there is less than 512 bytes to send.

    Is there a more elegant way to write this? How can I determine that nothing
    more is being sent?

    Vic
    Victor Norman, Oct 8, 2004
    #1
    1. Advertising


  2. > Is there a more elegant way to write this? How can I determine that nothing
    > more is being sent?


    Write a better protocol. A better protocol is easy (it can be done
    better, but this is short and will do the job).

    - Josiah



    from StringIO import StringIO

    class my_dispatcher_with_send(asyncore.dispatcher_with_send):
    def send (self, data):
    asyncore.dispatcher_with_send(struct.pack('>L', len(data))+data)

    def read(sock, length):
    s = StringIO()
    while s.tell() < length:
    s.write(sock.recv(length-s.tell()))
    return s.getvalue()

    def receiver(sock):
    try:
    l = read(sock, 4)
    l = struct.unpack('>L', l)[0]
    r = read(sock, l)
    sock.close()
    return r
    except socket.error, why:
    sock.close()
    Josiah Carlson, Oct 8, 2004
    #2
    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. Mr Newbie
    Replies:
    3
    Views:
    571
    Brock Allen
    Sep 22, 2005
  2. Chris Berg
    Replies:
    4
    Views:
    7,595
    X_AWemner_X
    Nov 21, 2003
  3. -
    Replies:
    2
    Views:
    387
    Alan Krueger
    Jul 29, 2005
  4. Freddie
    Replies:
    2
    Views:
    415
    Freddie
    Jul 8, 2004
  5. nobody
    Replies:
    0
    Views:
    129
    nobody
    Jan 25, 2013
Loading...

Share This Page