how to read data from a socket given a file descriptor

Discussion in 'Python' started by Rajarshi Guha, Apr 7, 2004.

  1. Hi,
    I'm writing some code using PyGTK2 that uses inpu_add_full() to watch a
    socket. I've included the code below. I have two questions:

    1) What does a condition == 16 mean? It does match any of the
    gtk.gdk.INPUT_* values. What is the use of the condition variable in the
    callback?

    2) The source variable in the call back is an fd. I have some trivial code
    that is able to read from a socket:

    while 1:
    sock.listen(1)
    conn = sock.accept()[0]
    got = conn.recv(20)
    if (got == 'close'): break
    conn.send('hello there %d' % (c))
    c += 1

    But how can I make this work when I get an fd?

    Thanks,

    --%<-------------------------------------------------------

    def process_socket_message(source, condition):

    if condition == gtk.gdk.INPUT_READ:
    print 'something to read'
    elif condition == gtk.gdk.INPUT_WRITE:
    print 'ok to write'
    elif condition == gtk.gdk.INPUT_EXCEPTION:
    print 'an exception occured on the socket'
    else:
    print 'I dont know what the condition means'

    conn = sock.accept()[0]
    got = conn.recv(20)
    print got
    return gtk.TRUE

    if __name__ == '__main__':

    gnome.init('xxx','xxx')
    widgets = WidgetsWrapper('gui.glade','toplevel', TopLevelHandlers)

    # set up the socket to get messages from a client
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.bind('/tmp/mysocket')

    # setup and input_add
    socket_handler_id = gtk.input_add_full(sock, gtk.gdk.INPUT_READ, process_socket_message)

    gtk.mainloop ()
     
    Rajarshi Guha, Apr 7, 2004
    #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. Patrick LeBoutillier

    Read/Write IO on socket file descriptor?

    Patrick LeBoutillier, Jul 19, 2003, in forum: Perl
    Replies:
    0
    Views:
    3,068
    Patrick LeBoutillier
    Jul 19, 2003
  2. hg
    Replies:
    1
    Views:
    5,317
  3. mbm

    [socket] test socket descriptor state

    mbm, Sep 27, 2007, in forum: C Programming
    Replies:
    2
    Views:
    429
    CBFalconer
    Sep 27, 2007
  4. jungleman
    Replies:
    6
    Views:
    1,710
    Jorgen Grahn
    Nov 8, 2011
  5. Patrick LeBoutillier

    Read/Write IO on socket file descriptor

    Patrick LeBoutillier, Jul 20, 2003, in forum: Perl Misc
    Replies:
    1
    Views:
    186
    A. Sinan Unur
    Jul 20, 2003
Loading...

Share This Page