9
class PygameListener(nanotubes.Listener):
11
A custom listener which tracks connections in a list. Connected sockets
12
are available via the connections attribute, and use the MessageProtocol
15
def __init__(self, (host, port)):
16
nanotubes.Listener.__init__(self, (host, port), nanotubes.MessageProtocol)
19
def broadcast(self, name, **kw):
21
Broadcast a message to all connected sockets.
23
for conn_ref in self.connections:
24
conn_ref().protocol.post(name, **kw)
28
Remove dead connections.
31
for conn_ref in self.connections:
32
if conn_ref() is not None:
33
connections.append(conn_ref)
34
self.connections[:] = connections
36
def handle_new(self, conn):
37
self.connections.append(weakref.ref(conn))
42
#start a server listening for connections on port 1984
43
server = PygameListener(('10.1.1.55',1984))
44
screen = pygame.display.set_mode((320,200))
48
#the SocketHandler must be polled regularly.
49
nanotubes.SocketHandler.poll()
50
for event in pygame.event.get():
51
if event.type == pygame.QUIT:
53
elif event.type == pygame.MOUSEMOTION:
54
#broadcast MOUSEMOTION events to all connected clients.
55
server.broadcast(event.type, **event.dict)
57
for conn_ref in server.connections:
58
#get a reference to the connection
60
#if the reference is dead, ignore it
61
if conn is None: continue
62
#recieved events are stored in .protocol.messages
63
for event_type, args in conn.protocol.messages:
64
#if recieved event is pygame.MOUSEMOTION, draw a pixel
65
if event_type == pygame.MOUSEMOTION:
66
screen.set_at(args['pos'], (255,255,255))
67
#remove messages from the connections queue.
68
conn.protocol.messages[:] = []
70
#cleanup and remove dead connections.
75
nanothreads.install(main())