[H-GEN] pyglet and socket events

Stephen Thorne stephen.thorne at gmail.com
Thu May 1 02:14:03 EDT 2008


On Thu, May 1, 2008 at 11:33 AM, Peter Robinson <pjr at itee.uq.edu.au> wrote:
>  Hi,
>  I am considering using pyglet for a visualisation that responds to
>  messages over a socket. The pyglet doco I have read doesn't say anything
>  about socket events. Anyone had any experience that would help me?

If you use pyglet.app.run() to run your pyglet application, which is
the recommended way now, it will automatically use the correct
EventLoop object. The one that I looked at was from
pyglet.app.xlib.XlibEventLoop.

You can substitute or subclass this event loop to do more than listen
for xlib events.

I would suggest that you would need to modify this section of code:
(I have no doubts at all that gmail will mangle the indentation)

            for display in displays:
                if xlib.XPending(display._display):
                    pending_displays = (display,)
                    break
            else:
                # None found; select on all file descriptors or timeout
                iwtd = self.get_select_files()
                pending_displays, _, _ = select.select(iwtd, (), (), sleep_time)

That code is relatively opaque (note the use of 'for/else' - very rare
in python code), but what it is essentially doing is figuring out if
any events are pending on the X server. The rest of the loop is
handling those events.

If you modified this code so that if there are XPending events, you
also did a nonblocking select() on your sockets, and if there are no
XPending events, just add your sockets to the list returned from
'get_select_files()' and then handle the results of that select
sanely, you would be able to do proper asynchronous network
communication from within the pyglet EventLoop.

Further work will involve adding and removing sockets from the event
loop. Global lists or a reference to the event loop somewhere will be
required for this.

Once you have your PeterRobinsonEventLoop subclass, you can either
call it explicitly (PeterRobinsonEventLoop().run()) or you can do
pyglet.app.EventLoop = PeterRobinsonEventLoop and then run
pyglet.app.run() normally.

Looking at this, it's tempting to sit down and write a version that
works within the twisted event loop. I think that will be relatively
easy to hack together, and would remove a lot of the work required in
manually handling the select.select() call...

-- 
Stephen Thorne

"Give me enough bandwidth and a place to sit and I will move the world."
 --Jonathan Lange




More information about the General mailing list