Python’s asynchronous frameworks, like asyncio, Tornado, and Twisted, are increasingly important for writing high-performance web applications. Even if you’re an experienced web programmer, you may lack a rigorous understanding of how these frameworks work and when to use them. Let’s see how asyncio's event loop works, and learn how to efficiently handle very large numbers of concurrent connections.
19. from autobahn import (WebSocketServerProtocol,!
WebSocketServerFactory)!
example.py
20. clients = set()!
!
class ChatProtocol(WebSocketServerProtocol):!
def onConnect(self):!
clients.add(self)!
!
def onMessage(self, msg):!
for c in clients:!
if c is not self:!
c.sendMessage(msg)!
!
def onClose(self):!
clients.remove(self)!
example.py
How is this called?
26. asyncio
magic
class BaseEventLoop(events.AbstractEventLoop):!
def run_forever(self):!
while True:!
event_list = self._selector.select()!
!
for fd, mask, data in event_list:!
reader, writer = data!
!
if reader and mask & EVENT_READ:!
self._ready.append(reader)!
!
if writer and mask & EVENT_WRITE:!
self._ready.append(writer)!
!
ntodo = len(self._ready)!
for i in range(ntodo):!
callback = self._ready.popleft()!
callback()!
accept_connection