Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

protocol.py 27KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. # -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Standard implementations of Twisted protocol-related interfaces.
  6. Start here if you are looking to write a new protocol implementation for
  7. Twisted. The Protocol class contains some introductory material.
  8. """
  9. import random
  10. from typing import Callable, Optional
  11. from zope.interface import implementer
  12. from twisted.internet import defer, error, interfaces
  13. from twisted.internet.interfaces import IAddress, ITransport
  14. from twisted.logger import _loggerFor
  15. from twisted.python import components, failure, log
  16. @implementer(interfaces.IProtocolFactory, interfaces.ILoggingContext)
  17. class Factory:
  18. """
  19. This is a factory which produces protocols.
  20. By default, buildProtocol will create a protocol of the class given in
  21. self.protocol.
  22. """
  23. protocol: "Optional[Callable[[], Protocol]]" = None
  24. numPorts = 0
  25. noisy = True
  26. @classmethod
  27. def forProtocol(cls, protocol, *args, **kwargs):
  28. """
  29. Create a factory for the given protocol.
  30. It sets the C{protocol} attribute and returns the constructed factory
  31. instance.
  32. @param protocol: A L{Protocol} subclass
  33. @param args: Positional arguments for the factory.
  34. @param kwargs: Keyword arguments for the factory.
  35. @return: A L{Factory} instance wired up to C{protocol}.
  36. """
  37. factory = cls(*args, **kwargs)
  38. factory.protocol = protocol
  39. return factory
  40. def logPrefix(self):
  41. """
  42. Describe this factory for log messages.
  43. """
  44. return self.__class__.__name__
  45. def doStart(self):
  46. """
  47. Make sure startFactory is called.
  48. Users should not call this function themselves!
  49. """
  50. if not self.numPorts:
  51. if self.noisy:
  52. _loggerFor(self).info("Starting factory {factory!r}", factory=self)
  53. self.startFactory()
  54. self.numPorts = self.numPorts + 1
  55. def doStop(self):
  56. """
  57. Make sure stopFactory is called.
  58. Users should not call this function themselves!
  59. """
  60. if self.numPorts == 0:
  61. # This shouldn't happen, but does sometimes and this is better
  62. # than blowing up in assert as we did previously.
  63. return
  64. self.numPorts = self.numPorts - 1
  65. if not self.numPorts:
  66. if self.noisy:
  67. _loggerFor(self).info("Stopping factory {factory!r}", factory=self)
  68. self.stopFactory()
  69. def startFactory(self):
  70. """
  71. This will be called before I begin listening on a Port or Connector.
  72. It will only be called once, even if the factory is connected
  73. to multiple ports.
  74. This can be used to perform 'unserialization' tasks that
  75. are best put off until things are actually running, such
  76. as connecting to a database, opening files, etcetera.
  77. """
  78. def stopFactory(self):
  79. """
  80. This will be called before I stop listening on all Ports/Connectors.
  81. This can be overridden to perform 'shutdown' tasks such as disconnecting
  82. database connections, closing files, etc.
  83. It will be called, for example, before an application shuts down,
  84. if it was connected to a port. User code should not call this function
  85. directly.
  86. """
  87. def buildProtocol(self, addr: IAddress) -> "Optional[Protocol]":
  88. """
  89. Create an instance of a subclass of Protocol.
  90. The returned instance will handle input on an incoming server
  91. connection, and an attribute "factory" pointing to the creating
  92. factory.
  93. Alternatively, L{None} may be returned to immediately close the
  94. new connection.
  95. Override this method to alter how Protocol instances get created.
  96. @param addr: an object implementing L{IAddress}
  97. """
  98. assert self.protocol is not None
  99. p = self.protocol()
  100. p.factory = self
  101. return p
  102. class ClientFactory(Factory):
  103. """
  104. A Protocol factory for clients.
  105. This can be used together with the various connectXXX methods in
  106. reactors.
  107. """
  108. def startedConnecting(self, connector):
  109. """
  110. Called when a connection has been started.
  111. You can call connector.stopConnecting() to stop the connection attempt.
  112. @param connector: a Connector object.
  113. """
  114. def clientConnectionFailed(self, connector, reason):
  115. """
  116. Called when a connection has failed to connect.
  117. It may be useful to call connector.connect() - this will reconnect.
  118. @type reason: L{twisted.python.failure.Failure}
  119. """
  120. def clientConnectionLost(self, connector, reason):
  121. """
  122. Called when an established connection is lost.
  123. It may be useful to call connector.connect() - this will reconnect.
  124. @type reason: L{twisted.python.failure.Failure}
  125. """
  126. class _InstanceFactory(ClientFactory):
  127. """
  128. Factory used by ClientCreator.
  129. @ivar deferred: The L{Deferred} which represents this connection attempt and
  130. which will be fired when it succeeds or fails.
  131. @ivar pending: After a connection attempt succeeds or fails, a delayed call
  132. which will fire the L{Deferred} representing this connection attempt.
  133. """
  134. noisy = False
  135. pending = None
  136. def __init__(self, reactor, instance, deferred):
  137. self.reactor = reactor
  138. self.instance = instance
  139. self.deferred = deferred
  140. def __repr__(self) -> str:
  141. return f"<ClientCreator factory: {self.instance!r}>"
  142. def buildProtocol(self, addr):
  143. """
  144. Return the pre-constructed protocol instance and arrange to fire the
  145. waiting L{Deferred} to indicate success establishing the connection.
  146. """
  147. self.pending = self.reactor.callLater(
  148. 0, self.fire, self.deferred.callback, self.instance
  149. )
  150. self.deferred = None
  151. return self.instance
  152. def clientConnectionFailed(self, connector, reason):
  153. """
  154. Arrange to fire the waiting L{Deferred} with the given failure to
  155. indicate the connection could not be established.
  156. """
  157. self.pending = self.reactor.callLater(
  158. 0, self.fire, self.deferred.errback, reason
  159. )
  160. self.deferred = None
  161. def fire(self, func, value):
  162. """
  163. Clear C{self.pending} to avoid a reference cycle and then invoke func
  164. with the value.
  165. """
  166. self.pending = None
  167. func(value)
  168. class ClientCreator:
  169. """
  170. Client connections that do not require a factory.
  171. The various connect* methods create a protocol instance using the given
  172. protocol class and arguments, and connect it, returning a Deferred of the
  173. resulting protocol instance.
  174. Useful for cases when we don't really need a factory. Mainly this
  175. is when there is no shared state between protocol instances, and no need
  176. to reconnect.
  177. The C{connectTCP}, C{connectUNIX}, and C{connectSSL} methods each return a
  178. L{Deferred} which will fire with an instance of the protocol class passed to
  179. L{ClientCreator.__init__}. These Deferred can be cancelled to abort the
  180. connection attempt (in a very unlikely case, cancelling the Deferred may not
  181. prevent the protocol from being instantiated and connected to a transport;
  182. if this happens, it will be disconnected immediately afterwards and the
  183. Deferred will still errback with L{CancelledError}).
  184. """
  185. def __init__(self, reactor, protocolClass, *args, **kwargs):
  186. self.reactor = reactor
  187. self.protocolClass = protocolClass
  188. self.args = args
  189. self.kwargs = kwargs
  190. def _connect(self, method, *args, **kwargs):
  191. """
  192. Initiate a connection attempt.
  193. @param method: A callable which will actually start the connection
  194. attempt. For example, C{reactor.connectTCP}.
  195. @param args: Positional arguments to pass to C{method}, excluding the
  196. factory.
  197. @param kwargs: Keyword arguments to pass to C{method}.
  198. @return: A L{Deferred} which fires with an instance of the protocol
  199. class passed to this L{ClientCreator}'s initializer or fails if the
  200. connection cannot be set up for some reason.
  201. """
  202. def cancelConnect(deferred):
  203. connector.disconnect()
  204. if f.pending is not None:
  205. f.pending.cancel()
  206. d = defer.Deferred(cancelConnect)
  207. f = _InstanceFactory(
  208. self.reactor, self.protocolClass(*self.args, **self.kwargs), d
  209. )
  210. connector = method(factory=f, *args, **kwargs)
  211. return d
  212. def connectTCP(self, host, port, timeout=30, bindAddress=None):
  213. """
  214. Connect to a TCP server.
  215. The parameters are all the same as to L{IReactorTCP.connectTCP} except
  216. that the factory parameter is omitted.
  217. @return: A L{Deferred} which fires with an instance of the protocol
  218. class passed to this L{ClientCreator}'s initializer or fails if the
  219. connection cannot be set up for some reason.
  220. """
  221. return self._connect(
  222. self.reactor.connectTCP,
  223. host,
  224. port,
  225. timeout=timeout,
  226. bindAddress=bindAddress,
  227. )
  228. def connectUNIX(self, address, timeout=30, checkPID=False):
  229. """
  230. Connect to a Unix socket.
  231. The parameters are all the same as to L{IReactorUNIX.connectUNIX} except
  232. that the factory parameter is omitted.
  233. @return: A L{Deferred} which fires with an instance of the protocol
  234. class passed to this L{ClientCreator}'s initializer or fails if the
  235. connection cannot be set up for some reason.
  236. """
  237. return self._connect(
  238. self.reactor.connectUNIX, address, timeout=timeout, checkPID=checkPID
  239. )
  240. def connectSSL(self, host, port, contextFactory, timeout=30, bindAddress=None):
  241. """
  242. Connect to an SSL server.
  243. The parameters are all the same as to L{IReactorSSL.connectSSL} except
  244. that the factory parameter is omitted.
  245. @return: A L{Deferred} which fires with an instance of the protocol
  246. class passed to this L{ClientCreator}'s initializer or fails if the
  247. connection cannot be set up for some reason.
  248. """
  249. return self._connect(
  250. self.reactor.connectSSL,
  251. host,
  252. port,
  253. contextFactory=contextFactory,
  254. timeout=timeout,
  255. bindAddress=bindAddress,
  256. )
  257. class ReconnectingClientFactory(ClientFactory):
  258. """
  259. Factory which auto-reconnects clients with an exponential back-off.
  260. Note that clients should call my resetDelay method after they have
  261. connected successfully.
  262. @ivar maxDelay: Maximum number of seconds between connection attempts.
  263. @ivar initialDelay: Delay for the first reconnection attempt.
  264. @ivar factor: A multiplicitive factor by which the delay grows
  265. @ivar jitter: Percentage of randomness to introduce into the delay length
  266. to prevent stampeding.
  267. @ivar clock: The clock used to schedule reconnection. It's mainly useful to
  268. be parametrized in tests. If the factory is serialized, this attribute
  269. will not be serialized, and the default value (the reactor) will be
  270. restored when deserialized.
  271. @type clock: L{IReactorTime}
  272. @ivar maxRetries: Maximum number of consecutive unsuccessful connection
  273. attempts, after which no further connection attempts will be made. If
  274. this is not explicitly set, no maximum is applied.
  275. """
  276. maxDelay = 3600
  277. initialDelay = 1.0
  278. # Note: These highly sensitive factors have been precisely measured by
  279. # the National Institute of Science and Technology. Take extreme care
  280. # in altering them, or you may damage your Internet!
  281. # (Seriously: <http://physics.nist.gov/cuu/Constants/index.html>)
  282. factor = 2.7182818284590451 # (math.e)
  283. # Phi = 1.6180339887498948 # (Phi is acceptable for use as a
  284. # factor if e is too large for your application.)
  285. # This is the value of the molar Planck constant times c, joule
  286. # meter/mole. The value is attributable to
  287. # https://physics.nist.gov/cgi-bin/cuu/Value?nahc|search_for=molar+planck+constant+times+c
  288. jitter = 0.119626565582
  289. delay = initialDelay
  290. retries = 0
  291. maxRetries = None
  292. _callID = None
  293. connector = None
  294. clock = None
  295. continueTrying = 1
  296. def clientConnectionFailed(self, connector, reason):
  297. if self.continueTrying:
  298. self.connector = connector
  299. self.retry()
  300. def clientConnectionLost(self, connector, unused_reason):
  301. if self.continueTrying:
  302. self.connector = connector
  303. self.retry()
  304. def retry(self, connector=None):
  305. """
  306. Have this connector connect again, after a suitable delay.
  307. """
  308. if not self.continueTrying:
  309. if self.noisy:
  310. log.msg(f"Abandoning {connector} on explicit request")
  311. return
  312. if connector is None:
  313. if self.connector is None:
  314. raise ValueError("no connector to retry")
  315. else:
  316. connector = self.connector
  317. self.retries += 1
  318. if self.maxRetries is not None and (self.retries > self.maxRetries):
  319. if self.noisy:
  320. log.msg("Abandoning %s after %d retries." % (connector, self.retries))
  321. return
  322. self.delay = min(self.delay * self.factor, self.maxDelay)
  323. if self.jitter:
  324. self.delay = random.normalvariate(self.delay, self.delay * self.jitter)
  325. if self.noisy:
  326. log.msg(
  327. "%s will retry in %d seconds"
  328. % (
  329. connector,
  330. self.delay,
  331. )
  332. )
  333. def reconnector():
  334. self._callID = None
  335. connector.connect()
  336. if self.clock is None:
  337. from twisted.internet import reactor
  338. self.clock = reactor
  339. self._callID = self.clock.callLater(self.delay, reconnector)
  340. def stopTrying(self):
  341. """
  342. Put a stop to any attempt to reconnect in progress.
  343. """
  344. # ??? Is this function really stopFactory?
  345. if self._callID:
  346. self._callID.cancel()
  347. self._callID = None
  348. self.continueTrying = 0
  349. if self.connector:
  350. try:
  351. self.connector.stopConnecting()
  352. except error.NotConnectingError:
  353. pass
  354. def resetDelay(self):
  355. """
  356. Call this method after a successful connection: it resets the delay and
  357. the retry counter.
  358. """
  359. self.delay = self.initialDelay
  360. self.retries = 0
  361. self._callID = None
  362. self.continueTrying = 1
  363. def __getstate__(self):
  364. """
  365. Remove all of the state which is mutated by connection attempts and
  366. failures, returning just the state which describes how reconnections
  367. should be attempted. This will make the unserialized instance
  368. behave just as this one did when it was first instantiated.
  369. """
  370. state = self.__dict__.copy()
  371. for key in [
  372. "connector",
  373. "retries",
  374. "delay",
  375. "continueTrying",
  376. "_callID",
  377. "clock",
  378. ]:
  379. if key in state:
  380. del state[key]
  381. return state
  382. class ServerFactory(Factory):
  383. """
  384. Subclass this to indicate that your protocol.Factory is only usable for servers.
  385. """
  386. class BaseProtocol:
  387. """
  388. This is the abstract superclass of all protocols.
  389. Some methods have helpful default implementations here so that they can
  390. easily be shared, but otherwise the direct subclasses of this class are more
  391. interesting, L{Protocol} and L{ProcessProtocol}.
  392. """
  393. connected = 0
  394. transport: Optional[ITransport] = None
  395. def makeConnection(self, transport):
  396. """
  397. Make a connection to a transport and a server.
  398. This sets the 'transport' attribute of this Protocol, and calls the
  399. connectionMade() callback.
  400. """
  401. self.connected = 1
  402. self.transport = transport
  403. self.connectionMade()
  404. def connectionMade(self):
  405. """
  406. Called when a connection is made.
  407. This may be considered the initializer of the protocol, because
  408. it is called when the connection is completed. For clients,
  409. this is called once the connection to the server has been
  410. established; for servers, this is called after an accept() call
  411. stops blocking and a socket has been received. If you need to
  412. send any greeting or initial message, do it here.
  413. """
  414. connectionDone = failure.Failure(error.ConnectionDone())
  415. connectionDone.cleanFailure()
  416. @implementer(interfaces.IProtocol, interfaces.ILoggingContext)
  417. class Protocol(BaseProtocol):
  418. """
  419. This is the base class for streaming connection-oriented protocols.
  420. If you are going to write a new connection-oriented protocol for Twisted,
  421. start here. Any protocol implementation, either client or server, should
  422. be a subclass of this class.
  423. The API is quite simple. Implement L{dataReceived} to handle both
  424. event-based and synchronous input; output can be sent through the
  425. 'transport' attribute, which is to be an instance that implements
  426. L{twisted.internet.interfaces.ITransport}. Override C{connectionLost} to be
  427. notified when the connection ends.
  428. Some subclasses exist already to help you write common types of protocols:
  429. see the L{twisted.protocols.basic} module for a few of them.
  430. """
  431. factory: Optional[Factory] = None
  432. def logPrefix(self):
  433. """
  434. Return a prefix matching the class name, to identify log messages
  435. related to this protocol instance.
  436. """
  437. return self.__class__.__name__
  438. def dataReceived(self, data: bytes):
  439. """
  440. Called whenever data is received.
  441. Use this method to translate to a higher-level message. Usually, some
  442. callback will be made upon the receipt of each complete protocol
  443. message.
  444. @param data: a string of indeterminate length. Please keep in mind
  445. that you will probably need to buffer some data, as partial
  446. (or multiple) protocol messages may be received! I recommend
  447. that unit tests for protocols call through to this method with
  448. differing chunk sizes, down to one byte at a time.
  449. """
  450. def connectionLost(self, reason: failure.Failure = connectionDone):
  451. """
  452. Called when the connection is shut down.
  453. Clear any circular references here, and any external references
  454. to this Protocol. The connection has been closed.
  455. @type reason: L{twisted.python.failure.Failure}
  456. """
  457. @implementer(interfaces.IConsumer)
  458. class ProtocolToConsumerAdapter(components.Adapter):
  459. def write(self, data: bytes):
  460. self.original.dataReceived(data)
  461. def registerProducer(self, producer, streaming):
  462. pass
  463. def unregisterProducer(self):
  464. pass
  465. components.registerAdapter(
  466. ProtocolToConsumerAdapter, interfaces.IProtocol, interfaces.IConsumer
  467. )
  468. @implementer(interfaces.IProtocol)
  469. class ConsumerToProtocolAdapter(components.Adapter):
  470. def dataReceived(self, data: bytes):
  471. self.original.write(data)
  472. def connectionLost(self, reason: failure.Failure):
  473. pass
  474. def makeConnection(self, transport):
  475. pass
  476. def connectionMade(self):
  477. pass
  478. components.registerAdapter(
  479. ConsumerToProtocolAdapter, interfaces.IConsumer, interfaces.IProtocol
  480. )
  481. @implementer(interfaces.IProcessProtocol)
  482. class ProcessProtocol(BaseProtocol):
  483. """
  484. Base process protocol implementation which does simple dispatching for
  485. stdin, stdout, and stderr file descriptors.
  486. """
  487. transport: Optional[interfaces.IProcessTransport] = None
  488. def childDataReceived(self, childFD: int, data: bytes):
  489. if childFD == 1:
  490. self.outReceived(data)
  491. elif childFD == 2:
  492. self.errReceived(data)
  493. def outReceived(self, data: bytes):
  494. """
  495. Some data was received from stdout.
  496. """
  497. def errReceived(self, data: bytes):
  498. """
  499. Some data was received from stderr.
  500. """
  501. def childConnectionLost(self, childFD: int):
  502. if childFD == 0:
  503. self.inConnectionLost()
  504. elif childFD == 1:
  505. self.outConnectionLost()
  506. elif childFD == 2:
  507. self.errConnectionLost()
  508. def inConnectionLost(self):
  509. """
  510. This will be called when stdin is closed.
  511. """
  512. def outConnectionLost(self):
  513. """
  514. This will be called when stdout is closed.
  515. """
  516. def errConnectionLost(self):
  517. """
  518. This will be called when stderr is closed.
  519. """
  520. def processExited(self, reason: failure.Failure):
  521. """
  522. This will be called when the subprocess exits.
  523. @type reason: L{twisted.python.failure.Failure}
  524. """
  525. def processEnded(self, reason: failure.Failure):
  526. """
  527. Called when the child process exits and all file descriptors
  528. associated with it have been closed.
  529. @type reason: L{twisted.python.failure.Failure}
  530. """
  531. class AbstractDatagramProtocol:
  532. """
  533. Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP,
  534. UDP.
  535. """
  536. transport = None
  537. numPorts = 0
  538. noisy = True
  539. def __getstate__(self):
  540. d = self.__dict__.copy()
  541. d["transport"] = None
  542. return d
  543. def doStart(self):
  544. """
  545. Make sure startProtocol is called.
  546. This will be called by makeConnection(), users should not call it.
  547. """
  548. if not self.numPorts:
  549. if self.noisy:
  550. log.msg("Starting protocol %s" % self)
  551. self.startProtocol()
  552. self.numPorts = self.numPorts + 1
  553. def doStop(self):
  554. """
  555. Make sure stopProtocol is called.
  556. This will be called by the port, users should not call it.
  557. """
  558. assert self.numPorts > 0
  559. self.numPorts = self.numPorts - 1
  560. self.transport = None
  561. if not self.numPorts:
  562. if self.noisy:
  563. log.msg("Stopping protocol %s" % self)
  564. self.stopProtocol()
  565. def startProtocol(self):
  566. """
  567. Called when a transport is connected to this protocol.
  568. Will only be called once, even if multiple ports are connected.
  569. """
  570. def stopProtocol(self):
  571. """
  572. Called when the transport is disconnected.
  573. Will only be called once, after all ports are disconnected.
  574. """
  575. def makeConnection(self, transport):
  576. """
  577. Make a connection to a transport and a server.
  578. This sets the 'transport' attribute of this DatagramProtocol, and calls the
  579. doStart() callback.
  580. """
  581. assert self.transport == None
  582. self.transport = transport
  583. self.doStart()
  584. def datagramReceived(self, datagram: bytes, addr):
  585. """
  586. Called when a datagram is received.
  587. @param datagram: the bytes received from the transport.
  588. @param addr: tuple of source of datagram.
  589. """
  590. @implementer(interfaces.ILoggingContext)
  591. class DatagramProtocol(AbstractDatagramProtocol):
  592. """
  593. Protocol for datagram-oriented transport, e.g. UDP.
  594. @type transport: L{None} or
  595. L{IUDPTransport<twisted.internet.interfaces.IUDPTransport>} provider
  596. @ivar transport: The transport with which this protocol is associated,
  597. if it is associated with one.
  598. """
  599. def logPrefix(self):
  600. """
  601. Return a prefix matching the class name, to identify log messages
  602. related to this protocol instance.
  603. """
  604. return self.__class__.__name__
  605. def connectionRefused(self):
  606. """
  607. Called due to error from write in connected mode.
  608. Note this is a result of ICMP message generated by *previous*
  609. write.
  610. """
  611. class ConnectedDatagramProtocol(DatagramProtocol):
  612. """
  613. Protocol for connected datagram-oriented transport.
  614. No longer necessary for UDP.
  615. """
  616. def datagramReceived(self, datagram):
  617. """
  618. Called when a datagram is received.
  619. @param datagram: the string received from the transport.
  620. """
  621. def connectionFailed(self, failure: failure.Failure):
  622. """
  623. Called if connecting failed.
  624. Usually this will be due to a DNS lookup failure.
  625. """
  626. @implementer(interfaces.ITransport)
  627. class FileWrapper:
  628. """
  629. A wrapper around a file-like object to make it behave as a Transport.
  630. This doesn't actually stream the file to the attached protocol,
  631. and is thus useful mainly as a utility for debugging protocols.
  632. """
  633. closed = 0
  634. disconnecting = 0
  635. producer = None
  636. streamingProducer = 0
  637. def __init__(self, file):
  638. self.file = file
  639. def write(self, data: bytes):
  640. try:
  641. self.file.write(data)
  642. except BaseException:
  643. self.handleException()
  644. def _checkProducer(self):
  645. # Cheating; this is called at "idle" times to allow producers to be
  646. # found and dealt with
  647. if self.producer:
  648. self.producer.resumeProducing()
  649. def registerProducer(self, producer, streaming):
  650. """
  651. From abstract.FileDescriptor
  652. """
  653. self.producer = producer
  654. self.streamingProducer = streaming
  655. if not streaming:
  656. producer.resumeProducing()
  657. def unregisterProducer(self):
  658. self.producer = None
  659. def stopConsuming(self):
  660. self.unregisterProducer()
  661. self.loseConnection()
  662. def writeSequence(self, iovec):
  663. self.write(b"".join(iovec))
  664. def loseConnection(self):
  665. self.closed = 1
  666. try:
  667. self.file.close()
  668. except OSError:
  669. self.handleException()
  670. def getPeer(self):
  671. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  672. # According to ITransport, this should return an IAddress!
  673. return "file", "file"
  674. def getHost(self):
  675. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  676. # According to ITransport, this should return an IAddress!
  677. return "file"
  678. def handleException(self):
  679. pass
  680. def resumeProducing(self):
  681. # Never sends data anyways
  682. pass
  683. def pauseProducing(self):
  684. # Never sends data anyways
  685. pass
  686. def stopProducing(self):
  687. self.loseConnection()
  688. __all__ = [
  689. "Factory",
  690. "ClientFactory",
  691. "ReconnectingClientFactory",
  692. "connectionDone",
  693. "Protocol",
  694. "ProcessProtocol",
  695. "FileWrapper",
  696. "ServerFactory",
  697. "AbstractDatagramProtocol",
  698. "DatagramProtocol",
  699. "ConnectedDatagramProtocol",
  700. "ClientCreator",
  701. ]