`
qiezi
  • 浏览: 498669 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

打算把twisted移植到D语言上

    博客分类:
  • D
阅读更多
twisted是一个优秀的python网络开发库,以前用它做过一个视频服务器,感觉它的接口应该比ACE更适合D一些。

twisted虽然是用python所写,但借助于Zope的interface模拟,很大程度上改善了动态语言开发的无接口约束的缺点。

由于它有一整套规范化的接口,所以应该先把它的接口转化过来,方便编写测试。简单看了一下TwistedCore,这个是twisted最基本的部分,先把twisted.internet转化过来吧。

python反射支持得不错,ZopeInterface也做了一些工作,所以可以利用它帮我完成一部分工作。我写了个脚本来转化这些接口:
from twisted.internet import interfaces;

def convert_interface(interface):
    result = "/**\n\t" + interface.__doc__ + "\n*/\n"
    result += "interface %s {\n" % interface.getName()
    for name, method in interface.namesAndDescriptions():
        result += "\t/**\n\t\t" + method.__doc__ + "\n\t*/\n"
        result += ("\tvoid %s%s;\n" % (name, method.getSignatureString()))
    result += "}\n\n\n\n"
    return result

output = "/**\n" + interfaces.__doc__ + "\n*/\n\n\n\n"

for interface in [x for x in dir(interfaces) if x[0] == "I"]:
    output += convert_interface(getattr(interfaces, interface))

print output

执行,输出结果如下:
/**
Interface documentation.

API Stability: stable, other than IReactorUDP (semi-stable) and
IReactorMulticast (unstable).

Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}

*/



/**
	An address, e.g. a TCP (host, port).

    Default implementations are in L{twisted.internet.address}.
    
*/
interface IAddress {
}



/**
	Object used to interface between connections and protocols.

    Each IConnector manages one connection.
    
*/
interface IConnector {
	/**
		Disconnect regardless of the connection state.

        If we are connected, disconnect, if we are trying to connect,
        stop trying.
        
	*/
	void disconnect();
	/**
		Try to connect to remote address.
	*/
	void connect();
	/**
		Stop attempting to connect.
	*/
	void stopConnecting();
	/**
		Return destination this will try to connect to.

        This will be an IAddress implementing object.
        
	*/
	void getDestination();
}



/**
	A consumer consumes data from a producer.
*/
interface IConsumer {
	/**
		Stop consuming data from a producer, without disconnecting.
        
	*/
	void unregisterProducer();
	/**
		Register to receive data from a producer.

        This sets self to be a consumer for a producer.  When this object
        runs out of data on a write() call, it will ask the producer
        to resumeProducing(). A producer should implement the L{IProducer}
        interface.   A push producer which is unable to pause or stop
        need not register or unregister.
        
	*/
	void registerProducer(producer, streaming);
	/**
		The producer will write data by calling this method.
	*/
	void write(data);
}



/**
	A scheduled call.

    There are probably other useful methods we can add to this interface;
    suggestions are welcome.
    
*/
interface IDelayedCall {
	/**
		Reset the scheduled call's timer.
        @param secondsFromNow: how many seconds from now it should fire,
            equivalent to C{self.cancel()} and then doing another
            C{reactor.callLater(secondsLater, ...)}

        @raises twisted.internet.error.AlreadyCalled: if the call has already
            happened.
        @raises twisted.internet.error.AlreadyCancelled: if the call has already
            been cancelled.
        
	*/
	void reset(secondsFromNow);
	/**
		Get time when delayed call will happen.

        @returns: time in seconds since epoch (a float).
        
	*/
	void getTime();
	/**
		Delay the scheduled call.
        @param secondsLater: how many seconds from its current firing time to delay

        @raises twisted.internet.error.AlreadyCalled: if the call has already
            happened.
        @raises twisted.internet.error.AlreadyCancelled: if the call has already
            been cancelled.
        
	*/
	void delay(secondsLater);
	/**
		
        @returns: True if this call is still active, False if it has been
            called or cancelled.
        
	*/
	void active();
	/**
		Cancel the scheduled call.

        @raises twisted.internet.error.AlreadyCalled: if the call has already
            happened.
        @raises twisted.internet.error.AlreadyCancelled: if the call has already
            been cancelled.
        
	*/
	void cancel();
}



/**
	A file descriptor.
    
*/
interface IFileDescriptor {
	/**
		fileno() -> int

        Returns: the platform-specified representation of a file-descriptor
        number.
        
	*/
	void fileno();
	/**
		Called when the connection was lost.

        This is called when the connection on a selectable object has been
        lost.  It will be called whether the connection was closed explicitly,
        an exception occurred in an event handler, or the other end of the
        connection closed it first.

        See also L{IHalfCloseableDescriptor} if your descriptor wants to be
        notified separately of the two halves of the connection being closed.
        
        @param reason: A failure instance indicating the reason why the
         connection was lost.  L{twisted.internet.error.ConnectionLost} and
         L{twisted.internet.error.ConnectionDone} are of special note, but
         the failure may be of other classes as well.
        
	*/
	void connectionLost(reason);
}



/**
	A Consumer for producers that finish.

    This interface is semi-stable.
    
*/
interface IFinishableConsumer {
	/**
		The producer has finished producing.
	*/
	void finish();
}



/**
	A descriptor that can be half-closed.
*/
interface IHalfCloseableDescriptor {
	/**
		Indicates read connection was lost.
	*/
	void readConnectionLost();
	/**
		Indicates write connection was lost.
	*/
	void writeConnectionLost();
}



/**
	Implemented to indicate they want notification of half-closes.

    TCP supports the notion of half-closing the connection, e.g.
    closing the write side but still not stopping reading. A protocol
    that implements this interface will be notified of such events,
    instead of having connectionLost called.
    
*/
interface IHalfCloseableProtocol {
	/**
		Notification of the write connection being closed.

        This will never be called for TCP connections as TCP does not
        support notification of this type of half-close.
        
	*/
	void writeConnectionLost();
	/**
		Notification of the read connection being closed.

        This indicates peer did half-close of write side. It is now
        the responsiblity of the this protocol to call
        loseConnection().  In addition, the protocol MUST make sure a
        reference to it still exists (i.e. by doing a callLater with
        one of its methods, etc.)  as the reactor will only have a
        reference to it if it is writing.

        If the protocol does not do so, it might get garbage collected
        without the connectionLost method ever being called.
        
	*/
	void readConnectionLost();
}



/**
	A listening port.
    
*/
interface IListeningPort {
	/**
		Stop listening on this port.

        If it does not complete immediately, will return Deferred that fires
        upon completion.
        
	*/
	void stopListening();
	/**
		Get the host that this port is listening for.

        @returns: a IAddress.
        
	*/
	void getHost();
	/**
		Start listening on this port.

        @raise CannotListenError: as defined here L{twisted.internet.error.CannotListenError},
                                  if it cannot listen on this port (e.g.,
                                  it is a TCP port and it cannot bind to
                                  the required port number)
        
	*/
	void startListening();
}



/**
	Additional functionality for multicast UDP.
*/
interface IMulticastTransport {
	/**
		Set interface for outgoing multicast packets.

        Returns Deferred of success.
        
	*/
	void setOutgoingInterface(addr);
	/**
		Return if loopback mode is enabled.
	*/
	void getLoopbackMode();
	/**
		Join a multicast group. Returns Deferred of success or failure.

        If an error occurs, the returned Deferred will fail with
        L{error.MulticastJoinError}.
        
	*/
	void joinGroup(addr, interface='');
	/**
		Set if loopback mode is enabled.
	*/
	void setLoopbackMode(mode);
	/**
		Set time to live on multicast packets.
	*/
	void setTTL(ttl);
	/**
		Return interface of outgoing multicast packets.
	*/
	void getOutgoingInterface();
	/**
		Leave multicast group, return Deferred of success.
	*/
	void leaveGroup(addr, interface='');
	/**
		Get time to live for multicast packets.
	*/
	void getTTL();
}



/**
	A process transport.

    @ivar pid: The Process-ID of this process.
    
*/
interface IProcessTransport {
	/**
		
        Close a file descriptor which is connected to the child process, identified
        by its FD in the child process.
        
	*/
	void closeChildFD(descriptor);
	/**
		Close stdout.
	*/
	void closeStdout();
	/**
		Close stdin after all data has been written out.
	*/
	void closeStdin();
	/**
		Send a signal to the process.

        @param signalID: can be
          - one of C{"HUP"}, C{"KILL"}, C{"STOP"}, or C{"INT"}.
              These will be implemented in a
              cross-platform manner, and so should be used
              if possible.
          - an integer, where it represents a POSIX
              signal ID.

        @raise twisted.internet.error.ProcessExitedAlready: The process has
        already exited.
        
	*/
	void signalProcess(signalID);
	/**
		Close stdin, stderr and stdout.
	*/
	void loseConnection();
	/**
		Close stderr.
	*/
	void closeStderr();
}



/**
	A producer produces data for a consumer.

    Typically producing is done by calling the write method of an
    object implementing L{IConsumer}.
    
*/
interface IProducer {
	/**
		Stop producing data.

        This tells a producer that its consumer has died, so it must stop
        producing data for good.
        
	*/
	void stopProducing();
}



/**
	
*/
interface IProtocol {
	/**
		Make a connection to a transport and a server.
        
	*/
	void makeConnection(transport);
	/**
		Called when the connection is shut down.

        Clear any circular references here, and any external references
        to this Protocol.  The connection has been closed. The reason
        Failure wraps a L{twisted.internet.error.ConnectionDone} or
        L{twisted.internet.error.ConnectionLost} instance (or a subclass
        of one of those).

        @type reason: L{twisted.python.failure.Failure}
        
	*/
	void connectionLost(reason);
	/**
		Called whenever data is received.

        Use this method to translate to a higher-level message.  Usually, some
        callback will be made upon the receipt of each complete protocol
        message.

        @param data: a string of indeterminate length.  Please keep in mind
            that you will probably need to buffer some data, as partial
            (or multiple) protocol messages may be received!  I recommend
            that unit tests for protocols call through to this method with
            differing chunk sizes, down to one byte at a time.
        
	*/
	void dataReceived(data);
	/**
		Called when a connection is made.

        This may be considered the initializer of the protocol, because
        it is called when the connection is completed.  For clients,
        this is called once the connection to the server has been
        established; for servers, this is called after an accept() call
        stops blocking and a socket has been received.  If you need to
        send any greeting or initial message, do it here.
        
	*/
	void connectionMade();
}



/**
	Interface for protocol factories.
    
*/
interface IProtocolFactory {
	/**
		Called when a connection has been established to addr.

        If None is returned, the connection is assumed to have been refused,
        and the Port will close the connection.

        @param addr: The address of the newly-established connection
        @type addr: (host, port)
        @returns: None if the connection was refused, otherwise an object
        implementing IProtocol.
        @rtype: None or L{IProtocol}.
        
	*/
	void buildProtocol(addr);
	/**
		Called every time this is connected to a Port or Connector.
	*/
	void doStart();
	/**
		Called every time this is unconnected from a Port or Connector.
	*/
	void doStop();
}



/**
	
    A pull producer, also known as a non-streaming producer, is
    expected to produce data each time resumeProducing() is called.

    This interface is semi-stable.
    
*/
interface IPullProducer {
	/**
		Produce data for the consumer a single time.

        This tells a producer to produce data for the consumer once
        (not repeatedly, once only). Typically this will be done
        by calling the consumer's write() method a single time with
        produced data.
        
	*/
	void resumeProducing();
}



/**
	
    A push producer, also known as a streaming producer is expected to
    produce (write to this consumer) data on a continous basis, unless
    it has been paused. A paused push producer will resume producing
    after its resumeProducing() method is called.   For a push producer
    which is not pauseable, these functions may be noops.

    This interface is semi-stable.
    
*/
interface IPushProducer {
	/**
		Resume producing data.

        This tells a producer to re-add itself to the main loop and produce
        more data for its consumer.
        
	*/
	void resumeProducing();
	/**
		Pause producing data.

        Tells a producer that it has produced too much data to process for
        the time being, and to stop until resumeProducing() is called.
        
	*/
	void pauseProducing();
}



/**
	
*/
interface IReactorArbitrary {
	/**
		Start an instance of the given C{portType} listening.

        @type portType: type which implements L{IListeningPort}
        @param portType: The object given by C{portType(*args, **kw)}
        will be started listening.
        
	*/
	void listenWith(portType, *args, **kw);
	/**
		
        Start an instance of the given C{connectorType} connecting.

        @type connectorType: type which implements L{IConnector}
        @param connectorType: The object given by C{connectorType(*args, **kw)}
        will be started connecting.
        
	*/
	void connectWith(connectorType, *args, **kw);
}



/**
	Core methods that a Reactor must implement.
    
*/
interface IReactorCore {
	/**
		Return a L{twisted.internet.defer.Deferred} that will resolve a hostname.
        
	*/
	void resolve(name, timeout=10);
	/**
		Stop the main loop *immediately*, without firing any system events.

        This is named as it is because this is an extremely "rude" thing to do;
        it is possible to lose data and put your system in an inconsistent
        state by calling this.  However, it is necessary, as sometimes a system
        can become wedged in a pre-shutdown call.
        
	*/
	void crash();
	/**
		Removes a trigger added with addSystemEventTrigger.

        @param triggerID: a value returned from addSystemEventTrigger.
        
	*/
	void removeSystemEventTrigger(triggerID);
	/**
		Fire 'shutdown' System Events, which will move the reactor to the
        'stopped' state and cause reactor.run() to exit. 
	*/
	void stop();
	/**
		Fire a system-wide event.

        System-wide events are things like 'startup', 'shutdown', and
        'persist'.
        
	*/
	void fireSystemEvent(eventType);
	/**
		Call a function when the reactor is running.

        If the reactor has not started, the callable will be scheduled
        to run when it does start. Otherwise, the callable will be invoked
        immediately.

        @param callable: the callable object to call later.

        @param args: the arguments to call it with.

        @param kw: the keyword arguments to call it with.

        @returns: None if the callable was invoked, otherwise a system
        event id for the scheduled call.
        
	*/
	void callWhenRunning(callable, *args, **kw);
	/**
		Run the main loop's I/O polling function for a period of time.

        This is most useful in applications where the UI is being drawn "as
        fast as possible", such as games. All pending L{IDelayedCall}s will
        be called.

        The reactor must have been started (via the run() method) prior to
        any invocations of this method.  It must also be stopped manually
        after the last call to this method (via the stop() method).  This
        method is not re-entrant: you must not call it recursively; in
        particular, you must not call it while the reactor is running.
        
	*/
	void iterate(delay=0);
	/**
		Fire 'startup' System Events, move the reactor to the 'running'
        state, then run the main loop until it is stopped with stop() or
        crash().
        
	*/
	void run();
	/**
		Add a function to be called when a system event occurs.

        Each "system event" in Twisted, such as 'startup', 'shutdown', and
        'persist', has 3 phases: 'before', 'during', and 'after' (in that
        order, of course).  These events will be fired internally by the
        Reactor.

        An implementor of this interface must only implement those events
        described here.

        Callbacks registered for the "before" phase may return either None or a
        Deferred.  The "during" phase will not execute until all of the
        Deferreds from the "before" phase have fired.

        Once the "during" phase is running, all of the remaining triggers must
        execute; their return values must be ignored.

        @param phase: a time to call the event -- either the string 'before',
                      'after', or 'during', describing when to call it
                      relative to the event's execution.

        @param eventType: this is a string describing the type of event.

        @param callable: the object to call before shutdown.

        @param args: the arguments to call it with.

        @param kw: the keyword arguments to call it with.

        @returns: an ID that can be used to remove this call with
                  removeSystemEventTrigger.
        
	*/
	void addSystemEventTrigger(phase, eventType, callable, *args, **kw);
}



/**
	Implement me to be able to use L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} type resources.

    This assumes that your main-loop uses UNIX-style numeric file descriptors
    (or at least similarly opaque IDs returned from a .fileno() method)
    
*/
interface IReactorFDSet {
	/**
		Removes an L{IWriteDescriptor} added with L{addWriter}.

        @returns: C{None}.
        
	*/
	void removeWriter(writer);
	/**
		I add reader to the set of file descriptors to get read events for.

        @param reader: An L{IReadDescriptor} that will be checked for read events
            until it is removed from the reactor with L{removeReader}.
        @returns: C{None}.
        
	*/
	void addReader(reader);
	/**
		I add writer to the set of file descriptors to get write events for.

        @param writer: An L{IWriteDescriptor} that will be checked for read events
            until it is removed from the reactor with L{removeWriter}.
        @returns: C{None}.
        
	*/
	void addWriter(writer);
	/**
		Remove all readers and writers, and return the list of
        L{IReadDescriptor}s and L{IWriteDescriptor}s removed.
        
        Should not remove reactor internal reactor connections (like a waker).
        
	*/
	void removeAll();
	/**
		Removes an L{IReadDescriptor} added with L{addReader}.

        @returns: C{None}.
        
	*/
	void removeReader(reader);
}



/**
	UDP socket methods that support multicast.

    IMPORTANT: This is an experimental new interface. It may change
    without backwards compatability. Suggestions are welcome.
    
*/
interface IReactorMulticast {
	/**
		Connects a given L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the given numeric UDP port.

        @param listenMultiple: boolean indicating whether multiple sockets can bind to same UDP port.
        @returns: object conforming to L{IListeningPort}.
        
	*/
	void listenMulticast(port, protocol, interface='', maxPacketSize=8192, listenMultiple=False);
}



/**
	A reactor with a pluggable name resolver interface.
    
*/
interface IReactorPluggableResolver {
	/**
		Set the internal resolver to use to for name lookups.

        @type resolver: An object implementing the L{IResolverSimple} interface
        @param resolver: The new resolver to use.
        
        @return: The previously installed resolver.
        
	*/
	void installResolver(resolver);
}



/**
	
*/
interface IReactorProcess {
	/**
		Spawn a process, with a process protocol.

        @param processProtocol: a L{twisted.internet.protocol.ProcessProtocol} instance

        @param executable: the file name to spawn - the full path should be
                           used.

        @param args: the command line arguments to pass to the process; a
                     sequence of strings. The first string should be the
                     executable's name.

        @param env: the environment variables to pass to the processs; a
                    dictionary of strings. If 'None', use os.environ.

        @param path: the path to run the subprocess in - defaults to the
                     current directory.

        @param uid: user ID to run the subprocess as. (Only available on
                    POSIX systems.)

        @param gid: group ID to run the subprocess as. (Only available on
                    POSIX systems.)

        @param usePTY: if true, run this process in a pseudo-terminal.
                       optionally a tuple of (masterfd, slavefd, ttyname),
                       in which case use those file descriptors.
                       (Not available on all systems.)

        @see: L{twisted.internet.protocol.ProcessProtocol}

        @returns: An L{IProcessTransport} object.

        @raise OSError: Raised with errno EAGAIN or ENOMEM if there are
        insufficient system resources to create a new process.
        
	*/
	void spawnProcess(processProtocol, executable, args=(), env={}, path=None, uid=None, gid=None, usePTY=0);
}



/**
	
*/
interface IReactorSSL {
	/**
		
        Connects a given protocol factory to the given numeric TCP/IP port.
        The connection is a SSL one, using contexts created by the context
        factory.

        @param port: a port number on which to listen

        @param factory: a L{twisted.internet.protocol.ServerFactory} instance

        @param contextFactory: a L{twisted.internet.ssl.ContextFactory} instance

        @param backlog: size of the listen queue

        @param interface: the hostname to bind to, defaults to '' (all)

        
	*/
	void listenSSL(port, factory, contextFactory, backlog=50, interface='');
	/**
		Connect a client Protocol to a remote SSL socket.

        @param host: a host name

        @param port: a port number

        @param factory: a L{twisted.internet.protocol.ClientFactory} instance

        @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.

        @param timeout: number of seconds to wait before assuming the connection
            has failed.

        @param bindAddress: a (host, port) tuple of local address to bind to, or
            C{None}.

        @returns: an L{IConnector}.
        
	*/
	void connectSSL(host, port, factory, contextFactory, timeout=30, bindAddress=None);
}



/**
	
*/
interface IReactorTCP {
	/**
		Connects a given protocol factory to the given numeric TCP/IP port.

        @param port: a port number on which to listen

        @param factory: a L{twisted.internet.protocol.ServerFactory} instance

        @param backlog: size of the listen queue

        @param interface: the hostname to bind to, defaults to '' (all)

        @returns: an object that satisfies the L{IListeningPort} interface

        @raise CannotListenError: as defined here L{twisted.internet.error.CannotListenError}, if it
           cannot listen on this port (e.g., it cannot bind to the required port
           number)
        
	*/
	void listenTCP(port, factory, backlog=50, interface='');
	/**
		Connect a TCP client.

        @param host: a host name

        @param port: a port number

        @param factory: a L{twisted.internet.protocol.ClientFactory} instance

        @param timeout: number of seconds to wait before assuming the
                        connection has failed.

        @param bindAddress: a (host, port) tuple of local address to bind
                            to, or None.

        @returns:  An object implementing L{IConnector}. This connector will call
           various callbacks on the factory when a connection is made,
           failed, or lost - see L{ClientFactory<twisted.internet.protocol.ClientFactory>} docs for details.
        
	*/
	void connectTCP(host, port, factory, timeout=30, bindAddress=None);
}



/**
	Dispatch methods to be run in threads.

    Internally, this should use a thread pool and dispatch methods to them.
    
*/
interface IReactorThreads {
	/**
		Run the callable object in a separate thread.
        
	*/
	void callInThread(callable, *args, **kwargs);
	/**
		Suggest the size of the thread pool.
        
	*/
	void suggestThreadPoolSize(size);
	/**
		Call a function from within another (i.e. non-reactor) thread.

        Use this method when you want to run a function in the reactor's thread
        from another thread.  Calling callFromThread should wake up the main
        thread (where reactor.run() is executing) and run the given callable in
        that thread.

        Obviously, the callable must be thread safe.  (If you want to call a
        function in the next mainloop iteration, but you're in the same thread,
        use callLater with a delay of 0.)
        
	*/
	void callFromThread(callable, *args, **kw);
}



/**
	Time methods that a Reactor should implement.
    
*/
interface IReactorTime {
	/**
		This method is deprecated.

        Cancel a call that would happen later.

        @param callID: this is an opaque identifier returned from C{callLater}
                       that will be used to cancel a specific call.

            @raise ValueError: if the callID is not recognized.
        
	*/
	void cancelCallLater(callID);
	/**
		Retrieve a list of all delayed calls.

        @returns: A tuple of all L{IDelayedCall} objects that are currently
                  scheduled. This is everything that has been returned by
                  C{callLater} but not yet called or canceled.
        
	*/
	void getDelayedCalls();
	/**
		Call a function later.

        @type delay:  C{float}
        @param delay: the number of seconds to wait.

        @param callable: the callable object to call later.

        @param args: the arguments to call it with.

        @param kw: the keyword arguments to call it with.

        @returns: An L{IDelayedCall} object that can be used to cancel
                  the scheduled call, by calling its C{cancel()} method.
                  It also may be rescheduled by calling its C{delay()}
                  or C{reset()} methods.
        
	*/
	void callLater(delay, callable, *args, **kw);
}



/**
	UDP socket methods.

    IMPORTANT: This is an experimental new interface. It may change
    without backwards compatability. Suggestions are welcome.
    
*/
interface IReactorUDP {
	/**
		Connects a given DatagramProtocol to the given numeric UDP port.

        @returns: object conforming to L{IListeningPort}.
        
	*/
	void listenUDP(port, protocol, interface='', maxPacketSize=8192);
	/**
		DEPRECATED.

        Connects a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance to a UDP port.
        
	*/
	void connectUDP(remotehost, remoteport, protocol, localport=0, interface='', maxPacketSize=8192);
}



/**
	UNIX socket methods.
*/
interface IReactorUNIX {
	/**
		Listen on a UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param factory: a L{twisted.internet.protocol.Factory} instance.

        @param backlog: number of connections to allow in backlog.

        @param mode: mode to set on the unix socket.

        @param wantPID: if True, create a pidfile for the socket.
        
	*/
	void listenUNIX(address, factory, backlog=50, mode=438, wantPID=0);
	/**
		Connect a client protocol to a UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param factory: a L{twisted.internet.protocol.ClientFactory} instance

        @param timeout: number of seconds to wait before assuming the connection
            has failed.

        @param checkPID: if True, check for a pid file to verify that a server
            is listening.

        @returns: an L{IConnector}.
        
	*/
	void connectUNIX(address, factory, timeout=30, checkPID=0);
}



/**
	datagram UNIX socket methods.
*/
interface IReactorUNIXDatagram {
	/**
		Listen on a datagram UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.

        @param maxPacketSize: maximum packet size to accept

        @param mode: mode to set on the unix socket.

        @returns: an L{IListeningPort}.
        
	*/
	void listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=438);
	/**
		Connect a client protocol to a datagram UNIX socket.

        @param address: a path to a unix socket on the filesystem.

        @param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance

        @param maxPacketSize: maximum packet size to accept

        @param mode: mode to set on the unix socket.

        @param bindAddress: address to bind to
        
	*/
	void connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=438, bindAddress=None);
}



/**
	
*/
interface IReadDescriptor {
	/**
		Some data is available for reading on your descriptor.
        
	*/
	void doRead();
}



/**
	I am a L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} that can both read and write.
    
*/
interface IReadWriteDescriptor {
}



/**
	
*/
interface IResolver {
	/**
		Lookup the AFSDB records associated with C{name}.
	*/
	void lookupAFSDatabase(name, timeout=10);
	/**
		Lookup the WKS records associated with C{name}.
	*/
	void lookupWellKnownServices(name, timeout=10);
	/**
		Lookup the MB records associated with C{name}.
	*/
	void lookupMailBox(name, timeout=10);
	/**
		Perform a zone transfer for the given C{name}.
	*/
	void lookupZone(name, timeout=10);
	/**
		Lookup all records associated with C{name}.
	*/
	void lookupAllRecords(name, timeout=10);
	/**
		Lookup the CNAME records associated with C{name}.
	*/
	void lookupCanonicalName(name, timeout=10);
	/**
		Interpret and dispatch a query object to the appropriate
        lookup* method.
        
	*/
	void query(query, timeout=10);
	/**
		Lookup the PTR records associated with C{name}.
	*/
	void lookupPointer(name, timeout=10);
	/**
		Lookup the MG records associated with C{name}.
	*/
	void lookupMailGroup(name, timeout=10);
	/**
		Lookup the RP records associated with C{name}.
	*/
	void lookupResponsibility(name, timeout=10);
	/**
		Lookup the MX records associated with C{name}.
	*/
	void lookupMailExchange(name, timeout=10);
	/**
		Lookup the NULL records associated with C{name}.
	*/
	void lookupNull(name, timeout=10);
	/**
		Lookup the records associated with the given name
           that are of the given type and in the given class.
        
	*/
	void lookupRecord(name, cls, type, timeout=10);
	/**
		Lookup the MR records associated with C{name}.
	*/
	void lookupMailRename(name, timeout=10);
	/**
		Lookup the TXT records associated with C{name}.
	*/
	void lookupText(name, timeout=10);
	/**
		Lookup the MINFO records associated with C{name}.
	*/
	void lookupMailboxInfo(name, timeout=10);
	/**
		Lookup the SRV records associated with C{name}.
	*/
	void lookupService(name, timeout=10);
	/**
		Lookup all the A6 records associated with C{name}.
	*/
	void lookupAddress6(name, timeout=10);
	/**
		Lookup all the AAAA records associated with C{name}.
	*/
	void lookupIPV6Address(name, timeout=10);
	/**
		Lookup the SOA records associated with C{name}.
	*/
	void lookupAuthority(name, timeout=10);
	/**
		Lookup the the NS records associated with C{name}.
	*/
	void lookupNameservers(name, timeout=10);
	/**
		Lookup the A records associated with C{name}.
	*/
	void lookupAddress(name, timeout=10);
	/**
		Lookup the HINFO records associated with C{name}.
	*/
	void lookupHostInfo(name, timeout=10);
}



/**
	
*/
interface IResolverSimple {
	/**
		Resolve the domain name C{name} into an IP address.

        @type name: C{str}
        @type timeout: C{tuple}
        @rtype: L{twisted.internet.defer.Deferred}
        @return: The callback of the Deferred that is returned will be
        passed a string that represents the IP address of the specified
        name, or the errback will be called if the lookup times out.  If
        multiple types of address records are associated with the name,
        A6 records will be returned in preference to AAAA records, which
        will be returned in preference to A records.  If there are multiple
        records of the type to be returned, one will be selected at random.

        @raise twisted.internet.defer.TimeoutError: Raised (asynchronously)
        if the name cannot be resolved within the specified timeout period.
        
	*/
	void getHostByName(name, timeout=(1, 3, 11, 45));
}



/**
	A SSL/TLS based transport.
*/
interface ISSLTransport {
	/**
		Return an object with the peer's certificate info.
	*/
	void getPeerCertificate();
}



/**
	An object which provides access to a collection of services.
*/
interface IServiceCollection {
	/**
		Add a service to this collection.
        
	*/
	void addService(service);
	/**
		Remove a service from this collection.
	*/
	void removeService(service);
	/**
		Retrieve the named service from this application.

        Raise a KeyError if there is no such service name.
        
	*/
	void getServiceNamed(serviceName);
}



/**
	An object that wraps a networking OS-specific handle.
*/
interface ISystemHandle {
	/**
		Return a system- and reactor-specific handle.

        This might be a socket.socket() object, or some other type of
        object, depending on which reactor is being used. Use and
        manipulate at your own risk.

        This might be used in cases where you want to set specific
        options not exposed by the Twisted APIs.
        
	*/
	void getHandle();
}



/**
	A TCP based transport.
*/
interface ITCPTransport {
	/**
		Return if SO_KEEPALIVE enabled.
	*/
	void getTcpKeepAlive();
	/**
		Half-close the write side of a TCP connection.
        
        If the protocol this is attached to implements
        IHalfCloseableProtocol, it will get notified when the
        operation is done. When closing write connection, as with
        loseConnection this will only happen when buffer has emptied
        and there is no registered producer.
        
	*/
	void loseWriteConnection();
	/**
		Returns IPv4Address.
	*/
	void getHost();
	/**
		Return if TCP_NODELAY is enabled.
	*/
	void getTcpNoDelay();
	/**
		Enable/disable TCP_NODELAY.

        Enabling TCP_NODELAY turns off Nagle's algorithm. Small packets are
        sent sooner, possibly at the expense of overall throughput.
	*/
	void setTcpNoDelay(enabled);
	/**
		Returns IPv4Address.
	*/
	void getPeer();
	/**
		Enable/disable SO_KEEPALIVE.

        Enabling SO_KEEPALIVE sends packets periodically when the connection
        is otherwise idle, usually once every two hours. They are intended
        to allow detection of lost peers in a non-infinite amount of time.
	*/
	void setTcpKeepAlive(enabled);
}



/**
	A TCP transport that supports switching to TLS midstream.

    Once TLS mode is started the transport will implement L{ISSLTransport}.
    
*/
interface ITLSTransport {
	/**
		Initiate TLS negotiation.

        @param contextFactory: A context factory (see L{ssl.py<twisted.internet.ssl>})
        
	*/
	void startTLS(contextFactory);
}



/**
	I am a transport for bytes.

    I represent (and wrap) the physical connection and synchronicity
    of the framework which is talking to the network.  I make no
    representations about whether calls to me will happen immediately
    or require returning to a control loop, or whether they will happen
    in the same or another thread.  Consider methods of this class
    (aside from getPeer) to be 'thrown over the wall', to happen at some
    indeterminate time.
    
*/
interface ITransport {
	/**
		
        Similar to getPeer, but returns an address describing this side of the
        connection.
        
	*/
	void getHost();
	/**
		Write some data to the physical connection, in sequence, in a
        non-blocking fashion.

        If possible, make sure that it is all written.  No data will
        ever be lost, although (obviously) the connection may be closed
        before it all gets through.
        
	*/
	void write(data);
	/**
		Return an L{IAddress}.

        Treat this method with caution.  It is the unfortunate
        result of the CGI and Jabber standards, but should not
        be considered reliable for the usual host of reasons;
        port forwarding, proxying, firewalls, IP masquerading,
        etcetera.
        
	*/
	void getPeer();
	/**
		Close my connection, after writing all pending data.

        Note that if there is a registered producer on a transport it
        will not be closed until the producer has been unregistered.
        
	*/
	void loseConnection();
	/**
		Write a list of strings to the physical connection.

        If possible, make sure that all of the data is written to
        the socket at once, without first copying it all into a
        single string.
        
	*/
	void writeSequence(data);
}



/**
	DEPRECATED. Transport for UDP ConnectedPacketProtocols.
*/
interface IUDPConnectedTransport {
	/**
		Write packet to address we are connected to.
	*/
	void write(packet);
	/**
		Returns UNIXAddress.
	*/
	void getHost();
}



/**
	Transport for UDP DatagramProtocols.
*/
interface IUDPTransport {
	/**
		Stop listening on this port.

        If it does not complete immediately, will return Deferred that fires
        upon completion.
        
	*/
	void stopListening();
	/**
		Write packet to given address.

        @param addr: a tuple of (ip, port). For connected transports must
                     be the address the transport is connected to, or None.
                     In non-connected mode this is mandatory.

        @raise twisted.internet.error.MessageLengthError: C{packet} was too
        long.
        
	*/
	void write(packet, addr=None);
	/**
		Connect the transport to an address.

        This changes it to connected mode. Datagrams can only be sent to
        this address, and will only be received from this address. In addition
        the protocol's connectionRefused method might get called if destination
        is not receiving datagrams.

        @param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
        @param port: port to connect to.
        
	*/
	void connect(host, port);
	/**
		Returns IPv4Address.
	*/
	void getHost();
}



/**
	Transport for UDP ConnectedPacketProtocols.
*/
interface IUNIXDatagramConnectedTransport {
	/**
		Write packet to address we are connected to.
	*/
	void write(packet);
	/**
		Returns UNIXAddress.
	*/
	void getPeer();
	/**
		Returns UNIXAddress.
	*/
	void getHost();
}



/**
	Transport for UDP PacketProtocols.
*/
interface IUNIXDatagramTransport {
	/**
		Write packet to given address.
	*/
	void write(packet, address);
	/**
		Returns UNIXAddress.
	*/
	void getHost();
}



/**
	
*/
interface IWriteDescriptor {
	/**
		Some data is available for reading on your descriptor.
        
	*/
	void doWrite();
}



/**
	
*/
interface Interface {
}

Wow..多了许多东西呀,而且方法签名没有类型,所以我还要手动改很多,不过文档都转过来了。
分享到:
评论
1 楼 qiezi 2007-01-07  
辛苦了几个晚上转换了一些文件,发现很不值得,要转换的东西太多了。自己从头写了个简单的select实现,1个小时就可以有个雏形,加入timer支持也很容易,只要把timer排序,再设置好select超时即可。

相关推荐

    twisted 从入门到精通

    此外,由于 Python 是跨平台的语言,Twisted 可以在不同的操作系统上运行,如 Linux、Windows、Unix 和 macOS 等。 ##### 1.2 异步与事件驱动 传统的同步网络编程方法通常会面临一个难题:要么程序在网络通信过程...

    twisted适合python3.8版本

    Twisted是Python编程语言中的一个开源网络框架,专注于异步编程和事件驱动的网络应用开发。这个框架在Python社区中广泛使用,特别是对于构建高性能、高并发的服务器端应用程序。标题提到"twisted适合python3.8版本...

    Twisted系列教程 的中文翻译

    通过这部分内容,读者可以对Twisted框架有一个全面的认识,并且能够体会到Twisted在与其它编程语言和模式结合时的独特优势。 整体而言,这系列教程是对Twisted框架的全面介绍,涵盖了从基础到高级的各个层面的知识...

    python3-Twisted

    Python3-Twisted是Python编程语言中的一个关键库,它为网络编程提供了强大的异步I/O框架。在Windows平台上,当尝试安装Scrapy这个高级Web爬虫框架时,可能会遇到依赖性问题,提示需要安装Twisted。这是因为Scrapy在...

    twisted系列教程-中文

    Twisted系列教程中文简介 Twisted是一个基于Python的异步网络编程库,提供了一个灵活的架构来处理异步I/O操作。该教程将从基础开始,逐步深入Twisted的世界,帮助读者了解异步编程的思想和Twisted的使用方法。 ...

    twisted 异步教程 中文版

    Twisted 是一个开源的事件驱动编程框架,它主要用Python语言编写,并被广泛用于网络协议的实现和异步编程。在Twisted框架中,Reactor模式是实现异步编程的核心组件,它是对观察者模式的实现,能够响应并处理不同类型...

    twisted introduction

    随后会深入到Twisted的低级方面,这些通常在日常编程中不会用到,但对理解Twisted的工作原理至关重要。 总结来说,文档通过逐步构建异步编程的心理模型,使新接触Twisted框架的开发者能够逐渐适应这种编程模式,并...

    Twisted与异步编程入门

    【Twisted与异步编程入门】是一篇关于Python中Twisted框架和异步编程的教程。Twisted是一个强大的网络应用框架,特别适用于处理复杂的异步编程需求。文章首先强调了理解异步编程模型的重要性,指出只有深入理解模型...

    twisted, vitualc++ 包

    标题中的“twisted, virtualc++ 包”指的是与Python编程语言相关的两个关键组件:Twisted框架和Visual C++编译器。Twisted是Python的一个网络应用框架,它提供了大量用于编写异步网络代码的库,包括服务器和客户端。...

    twisted例子

    Twisted是一个强大的Python异步网络编程框架,广泛用于构建复杂的、高性能的网络应用程序。这个"twisted例子"可能是一个从Twisted系列教程中提取的实际应用示例,旨在帮助学习者更好地理解和掌握Twisted的核心概念和...

    Twisted适配python3.5

    然而,描述中提到,Scrapy——一个基于Twisted的Python爬虫框架,在某个时间点仅支持Python 2.7到3.4版本,不包括Python 3.5,这可能会导致在尝试在Python 3.5环境下运行Scrapy时遇到兼容性问题。 在Python的生态...

    twisted入门教程源码

    **Twisted 框架详解** Twisted 是一个开源的 Python 网络编程框架,专为异步网络编程设计,广泛应用于网络服务、客户端、协议实现和并发处理。其核心设计围绕事件驱动模型,使得开发者可以编写高性能、高并发的网络...

    Twisted系列教程.pdf

    ### Twisted系列教程知识点概述 #### 第一部分:Twisted理论基础 - **前言**:这一部分主要介绍了Twisted框架的背景以及对于那些寻求快速入门的读者来说,Twisted可能并非是一个简单易学的选择。作者指出,对于希望...

    twisted whl安装包 v 17.9.0包含python2.7-3.7

    标题中的“twisted whl安装包 v 17.9.0包含python2.7-3.7”指的是Twisted库的一个特定版本——17.9.0,它以wheel(whl)格式提供,适用于Python 2.7到3.7的不同版本。在Python的生态系统中,whl是一种预编译的二进制...

    【批量下载】Twisted-历史各版本.zip

    Twisted 是一个强大的开源Python网络编程框架,专为异步编程设计。这个压缩包文件包含了Twisted的历史各版本,对于那些需要旧版本Twisted的开发者来说尤其有价值,因为官方已经停止提供旧版本的直接下载。 在Python...

    Twisted事件驱动网络框架

    **Twisted事件驱动网络框架详解** Twisted是一个强大的开源Python库,主要用于构建异步网络应用程序。这个框架基于事件驱动的设计模式,使得它非常适合处理大量并发连接,尤其在服务器端编程中,可以高效地处理I/O...

    twisted网络编程.txt

    4. **端口(Port)**:绑定到特定端口上的协议实例。 5. **连接(Connectors)**:用于发起连接尝试的组件。 6. **监听器(Listeners)**:负责接收传入连接请求的组件。 #### 三、安装与配置Twisted 1. **基本安装**: ...

    Twisted 17.9.0

    在32位和64位系统的支持上,Twisted 17.9.0通过提供不同架构的安装包,确保无论是在资源有限的环境还是在高性能服务器上,都能高效运行。安装过程可以通过whl文件进行,这是一种预先编译的Python包格式,可以快速...

    适合python3.8的Twisted

    在Windows 64位操作系统上,针对Python 3.8的特定版本是`Twisted-19.10.0-cp38-cp38-win_amd64`,这里的`cp38`表示兼容Python 3.8版本,`win_amd64`则表明是适用于64位Windows系统的构建。文件名为`.whl`的格式,这...

Global site tag (gtag.js) - Google Analytics