how to read data from a socket given a file descriptor

Rajarshi Guha rajarshi at presidency.com
Wed Apr 7 12:10:04 EDT 2004


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 ()



More information about the Python-list mailing list