美文网首页
<Twisted Network Programming

<Twisted Network Programming

作者: bluescorpio | 来源:发表于2018-09-05 20:13 被阅读51次
    1. The best way to learn about the components of a Twisted application is to dive right into some examples
    2. To test this pair of scripts, first run the server in one terminal with /python echoserv‐ er.py/. This will start a TCP server listening for connections on port 8000. Then run the client in a second terminal with /python echoclient.py/.
    3. In an event-driven program, program flow is determined by external events.
    4. It is char‐ acterized by an /event loop/and the use of callbacks to trigger actions when events happen.
    5. In the single-threaded synchronous version of the program, tasks are performed serially. If one task blocks on I/O, all of the other tasks must also wait. Single-threaded programs are thus easy to reason about but can be unnecessarily slow.
    6. In the multithreaded version, the three blocking tasks are performed in separate threads of control, which may run interleaved on one or many processors. This allows progress to be made by some threads while others are blocking on resources and is often more time-efficient than the analogous synchronous program. However, one has to write code that protects shared resources that could be accessed concurrently from multiple threads, which when implemented improperly can lead to notoriously subtle and pain‐ ful threading bugs.
    7. The event-driven version of the program interleaves the execution of the three tasks, but in a single thread of control. When performing I/O or other expensive operations, a callback is registered with an event loop, and then execution continues while the I/O completes. The callback describes how to handle an event once it has completed. The event loop polls for events and dispatches them as they arrive to the callbacks that are waiting for them. This allows the program to make progress without the use of addi‐ tional threads.
    8. The core of Twisted is the reactor event loop. The reactor knows about network, file‐ system, and timer events. It waits on and demultiplexes these events and dispatches them to waiting event handlers. Twisted takes care of abstracting away platform-specific behavior and using the underlying nonblocking APIs correctly. Twisted presents a common interface to the various event sources so that responding to events anywhere in the network stack is easy.
    9. After those callbacks have been registered, we start the reactor’s event loop with reactor.run. Once running, the reactor will poll for and dispatch events forever or until reactor.stop is called
    10. A /transport/represents the connection between two endpoints communicating over a network. Transports describe connection details: for example, is this connection stream- oriented (like TCP) or datagram-oriented (like UDP)? TCP, UDP, Unix sockets, and serial ports are examples of transports.
    11. /Protocols/describe how to process network events asynchronously. Twisted maintains implementations for many popular application protocols, including HTTP, Telnet, DNS, and IMAP. Protocols implement the IProtocol interface
    12. The call to connectTCP creates a TCP connection to the server on port 8000 and registers callbacks for the various stages of the connection
    13. A new instance of our Echo protocol class is instantiated for every connection and goes away when the connection terminates. This means that persistent configuration infor‐ mation is not saved in the protocol.
    14. Persistent configuration information is instead kept in an EchoFactory class, which inherits from protocol.Factory in the server and protocol.ClientFactory in the client. A factory’s buildProtocol method creates a protocol for each new connection, which gets passed to the reactor to register callbacks.
    15. Persistent protocol state is kept in the factory. Because a new instance of a protocol class is created for each connection, protocols
      can’t contain persistent state; that information must instead be stored in a protocol factory
    16. It is common for a factory’s buildProtocol method to do nothing beyond return an instance of a Protocol.
    17. Protocols can retrieve the reason why a connection was terminated.
    18. Clients can make many simultaneous connections to a server.
      1. Define a protocol class, subclassing twisted.internet.protocol.Protocol for arbitrary data or twisted.protocols.basic.LineReceiver for line-oriented pro‐ tocols.
      1. Define a factory class, subclassing twisted.internet.protocol.Factory for servers and twisted.internet.protocol.ClientFactory for clients. That factory creates instances of the protocol and stores state shared across protocol instances.
      1. Clients use reactor.connectTCP to initiate a connection to a server. Invoking connectTCP registers callbacks with the reactor to notify your protocol when new data has arrived across a socket for processing. Servers use reactor.listenTCP to listen for and respond to client connections.
      1. Communication doesn’t start until reactor.run is called, which starts the reactor event loop.
    19. Callbacks are a fundamental part of event-driven programming and are the way that the reactor indicates to an application that an event has arrived.
    20. Deferreds do not automatically make code asynchronous or nonblocking. To turn a synchronous function into an asynchronous function, it’ll need to be refac‐ tored to return a Deferred with which callbacks are registered.
    21. Deferreds have a pair of callback chains, one for success (callbacks) and one for errors (errbacks). Deferreds start out with two empty chains. You add pairs of callbacks and errbacks to the Deferred to handle successes and failures at each point in the event processing. When an asynchronous result arrives, the Deferred is “fired” and the ap‐ propriate callbacks or errbacks are invoked in the order in which they were added to the chains.
    22. A Failure is Twisted’s implementation of a dressed-up Exception suitable for asyn‐ chronous communication. It contains a stack trace for where an asynchronous error actually happened (which might not be the current stack trace).
    23. To register multiple levels of callbacks and errbacks with a Deferred, simply attach them to their callback chains in the order you want them invoked using addCallback and addErrback
    24. Deferreds also sport an addCallbacks method, which registers both a callback and an errback at the same level in their respective callback chains.
    25. The salient difference is that callbacks and errbacks registered together using addCallbacks /do not interact.
    26. The HyperText Transfer Protocol (HTTP) is a request/response application-layer pro‐ tocol, where requests are initiated by a client to a server, which responds with the re‐ quested resource.
    27. A resource must provide the IResource interface, which describes how the resource gets rendered and how child resources in the resource hierarchy are added and accessed.
    28. We implement a render_ method for every HTTP method we want to support;
    29. In general, only resources that are leaves are rendered; this can be because isLeaf is set to True or because when traversing the resource hierarchy, that resource is where we are when the URL runs out.
    30. A service is anything that can be started and stopped and that implements the IService interface. Twisted comes with service implementations for TCP, FTP, HTTP, SSH, DNS, and many other protocols. Many services can register with a single application.
    31. An application is the top-level container for one or more services that are deployed together. Services register themselves with an application
    32. FileLogObserver.emit is an observer. Whenever log.msg or log.err is called, ob‐ servers registered through log.addObserver receive that event.
    33. Twisted does not automatically make your code asynchronous or nonblocking.
    34. Twisted provides helper modules in twisted.test for unit-testing clients and servers. Chief amongst them is proto_helpers, which has a StringTransport class for mocking transports.
    35. /trial/runs your test suite in a single thread, with a single reactor. This means that if a test ever leaves an event source (like a timer, socket, or misplaced Deferred) inside the reactor, it can affect future tests.

    相关文章

      网友评论

          本文标题:<Twisted Network Programming

          本文链接:https://www.haomeiwen.com/subject/tbszwftx.html