`
qiezi
  • 浏览: 491506 次
  • 性别: 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超时即可。

相关推荐

Global site tag (gtag.js) - Google Analytics