Advertisement
Guest User

Untitled

a guest
Jan 9th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. import weakref
  2. from twisted.internet import reactor
  3. from twisted.internet.endpoints import TCP4ServerEndpoint
  4. from twisted.python.sendmsg import getsockfam
  5. from twisted.internet.protocol import Factory, Protocol
  6. import twisted.internet.abstract
  7.  
  8. class EchoProtocol(Protocol):
  9.     def dataReceived(self, data):
  10.         self.transport.write(data)
  11.  
  12. class EchoFactory(Factory):
  13.     protocol = EchoProtocol
  14.  
  15. class TransferProtocol(Protocol):
  16.     def dataReceived(self, data):
  17.         self.transport.write('main process still listening!: %s' % (data))
  18.  
  19.     def connectionMade(self):
  20.         self.transport.write('this message should make it to the subprocess\n')
  21.  
  22.         # attempt 1: do nothing
  23.         #    everything works fine in the adopt (including receiving the written message), but old protocol still exists (though isn't doing anything)
  24.  
  25.         # attempt 1: try calling loseConnection
  26.         #    we lose connection before the adopt opens the socket (presumably TCP disconnect message was sent)
  27.         #
  28.         # self.transport.loseConnection()
  29.  
  30.         # attempt 2: try calling abortConnection
  31.         #    result is same as loseConnection
  32.         #
  33.         # self.transport.abortConnection()
  34.  
  35.         # attempt 3: try monkey patching the socket close out and calling loseConnection
  36.         #    result: same as doing nothing-- adopt works (including receiving the written message), old protocol still exists
  37.         #
  38.         # def ignored(*args, **kwargs):
  39.         #       print 'ignored :D'
  40.         #
  41.         # self.transport._closeSocket = ignored
  42.         # self.transport.loseConnection()
  43.  
  44.         reactor.callLater(0, adopt, self.transport.fileno())
  45.  
  46. class ServerFactory(Factory):
  47.     def buildProtocol(self, addr):
  48.         p = TransferProtocol()
  49.         self.ref = weakref.ref(p)
  50.         return p
  51.  
  52. f = ServerFactory()
  53.  
  54. def adopt(fileno):
  55.     print "does old protocol still exist?: %r" % (f.ref())
  56.     reactor.adoptStreamConnection(fileno, getsockfam(fileno), EchoFactory())
  57.  
  58. port = 1337
  59. endpoint = TCP4ServerEndpoint(reactor, port)
  60. d = endpoint.listen(f)
  61. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement