def testShortFileListings(self): # Connect client = ftp.FTPClient(passive=self.passive) factory = ClientFactory() factory.noisy = 0 factory.buildProtocol = lambda s, c=client: c reactor.connectTCP('localhost', self.ftp_port, factory) # Issue the command and set the callbacks p = BufferingProtocol() d = client.nlst('.', p) d.addCallbacks(self.callback, self.errback) # Wait for the result id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze while not hasattr(self, 'result') and not hasattr(self, 'error'): reactor.iterate() try: id.cancel() except ValueError: pass error = getattr(self, 'error', None) if error: raise error[0], error[1], error[2] # Check that the listing contains this file (ftp_crap) filenames = p.buf.getvalue().split('\r\n') self.failUnless('ftp_crap' in filenames, 'ftp_crap not in file listing')
def dataReceived(self, data): _q_s.logs.info([ "servers", { 'server': 'http_proxy_server', 'action': 'connection', 'ip': self.transport.getPeer().host, 'port': self.transport.getPeer().port } ]) try: ip = self.resolve_domain(data) if ip: factory = ClientFactory() factory.CustomProtocolParent_ = self factory.protocol = CustomProtocolChild reactor.connectTCP(ip, 80, factory) else: self.transport.loseConnection() if self.client: self.client.write(data) else: self.buffer = data except: pass
def test_getLogFiles(self): """ The reactor returned by L{loggedReactor} has a C{getLogFiles} method which returns a L{logstate} instance containing the active and completed log files tracked by the logging wrapper. """ wrapped = ClientFactory() wrapped.protocol = Discard reactor = MemoryReactor() logged = loggedReactor(reactor) logged.connectTCP('127.0.0.1', 1234, wrapped) factory = reactor.tcpClients[0][2] finished = factory.buildProtocol(None) finished.makeConnection(StringTransport()) finished.dataReceived('finished') finished.connectionLost(None) active = factory.buildProtocol(None) active.makeConnection(StringTransport()) active.dataReceived('active') logs = logged.getLogFiles() self.assertEqual(1, len(logs.finished)) self.assertIn('finished', logs.finished[0].getvalue()) self.assertEqual(1, len(logs.active)) self.assertIn('active', logs.active[0].getvalue())
def test_send_peh_upon_connection(self): '''To test client protocol we isloate it from the ClientFactory''' with patch.object(datetime, 'datetime', Mock(wraps=datetime.datetime)) as patched: fixed_date = datetime.datetime(2014, 1, 1, 12, 0, 0) patched.now.return_value = fixed_date factory = ClientFactory() factory.comaster = self.comaster factory.protocol = MaraClientProtocol proto = factory.buildProtocol(('127.0.0.1', 0)) proto.construct = MaraFrame # Disable unnesesary behaviour def stop(): proto.stop() reactor.stop() proto.sendPoll = MagicMock(side_effect=stop) transport = proto_helpers.StringTransport() proto.makeConnection(transport) bytes_sent_to_device = transport.value() result = MaraFrame.parse(bytes_sent_to_device) self.assertEqual(result.dest, 0xFF) self.assertEqual(result.source, 2) # We don't need to check BCC since it's already coded into MaraFrame self.assertEqual(result.peh, fixed_date) reactor.run() # Shuld have stopped self.assertEqual(self.comaster.update_peh_timestamp.call_count, 1) self.assertEqual(self.comaster.update_peh_timestamp.call_args[0][0], fixed_date)
def test_connectTCP(self): """ Called on the object returned by L{loggedReactor}, C{connectTCP} calls the wrapped reactor's C{connectTCP} method with the original factory wrapped in a L{_TrafficLoggingFactory}. """ class RecordDataProtocol(Protocol): def dataReceived(self, data): self.data = data proto = RecordDataProtocol() factory = ClientFactory() factory.protocol = lambda: proto reactor = MemoryReactor() logged = loggedReactor(reactor) logged.connectTCP('192.168.1.2', 1234, factory, 21, '127.0.0.2') [(host, port, factory, timeout, bindAddress)] = reactor.tcpClients self.assertEqual('192.168.1.2', host) self.assertEqual(1234, port) self.assertIsInstance(factory, _TrafficLoggingFactory) self.assertEqual(21, timeout) self.assertEqual('127.0.0.2', bindAddress) # Verify that the factory and protocol specified are really being used protocol = factory.buildProtocol(None) protocol.makeConnection(None) protocol.dataReceived("foo") self.assertEqual(proto.data, "foo")
def testRetr(self): # Connect client = ftp.FTPClient(passive=self.passive) factory = ClientFactory() factory.noisy = 0 factory.buildProtocol = lambda s, c=client: c reactor.connectTCP('localhost', self.ftp_port, factory) # download ftp_crap proto = BufferingProtocol() d = client.retr(os.path.basename('ftp_crap'), proto) d.addCallbacks(self.callback, self.errback) # Wait for a result id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze while not hasattr(self, 'result') and not hasattr(self, 'error'): reactor.iterate() try: id.cancel() except ValueError: pass error = getattr(self, 'error', None) if error: raise error[0], error[1], error[2] # Check that the file is the same as read directly off the disk self.failUnless(type(self.result) == types.ListType, 'callback result is wrong type: ' + str(self.result)) data = proto.buf.getvalue() self.failUnless(data == open('ftp_crap', "rb").read(), 'RETRieved file does not match original')
def writeBeforeHandshakeTest(self, sendingProtocol, bytes): """ Run test where client sends data before handshake, given the sending protocol and expected bytes. """ clientFactory = ClientFactory() clientFactory.protocol = sendingProtocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes)) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEqual("".join(serverProtocol.received), bytes) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred
def main(): P = OptionParser(usage="%prog [-C|-S] <-v> host:port") P.add_option('-v','--verbose', action='count', default=0, help='Print more information') P.add_option('-C','--client', action='store_true', default=True, dest='dir', help='Act as Client to PSC') P.add_option('-S','--server', action='store_false', dest='dir', help='Act as Server to IOC') vals, args = P.parse_args() if len(args)<1: P.usage() sys.exit(1) host, _, port = args[0].partition(':') port = int(port or '6') logging.basicConfig(level=_V.get(vals.verbose, 0)) if vals.dir: # Client log.info('Connect to %s:%u', host, port) fact = ClientFactory() fact.protocol = PSCClient ep = reactor.connectTCP(host, port, fact) else: # Server log.info('Serve from %s:%u', host, port) fact = Factory() fact.protocol = PSCServer ep = reactor.listenTCP(port, fact, interface=host or '') log.info('Run') reactor.run() log.info('Done')
def testStor(self): # Connect client = ftp.FTPClient(passive=self.passive) client.debug = 1 factory = ClientFactory() factory.noisy = 0 factory.buildProtocol = lambda s, c=client: c reactor.connectTCP('localhost', self.ftp_port, factory) expectedContent = "Hello\n"*4 def gotResult(c): c.write(expectedContent) c.finish() def gotErr(f): self.errback(f) t = client.storeFile("HelloThere") t[0].addCallbacks(gotResult, gotErr) t[1].addCallbacks(self.callback, self.errback) # Wait for a result id = reactor.callLater(5, self.errback, "timed out") # timeout so we don't freeze while not hasattr(self, 'result') and not hasattr(self, 'error'): reactor.iterate() try: id.cancel() except ValueError: pass error = getattr(self, 'error', None) if error: raise error[0], error[1], error[2] self.assertEquals(open('HelloThere').read(), expectedContent)
def test_handshake(self): """ The TLS handshake is performed when L{TLSMemoryBIOProtocol} is connected to a transport. """ clientFactory = ClientFactory() clientFactory.protocol = Protocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverFactory = ServerFactory() serverFactory.protocol = Protocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Only wait for the handshake to complete. Anything after that isn't # important here. return handshakeDeferred
def test_disorderlyShutdown(self): """ If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is reported to the application. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol(clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) # Client speaks first, so the server can be dumb. serverProtocol = Protocol() connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol) # Now destroy the connection. serverProtocol.transport.loseConnection() # And when the connection completely dies, check the reason. def cbDisconnected(clientProtocol): clientProtocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbDisconnected) return clientConnectionLost
def clientConnectionLost(self, connector, unused_reason): self.clientProxy.nodeLocator.remove(self.address) if hasattr(self, 'deferred') and not self.deferred.called: self.reactor.callLater(0, self.deferred.errback, unused_reason) del self.deferred ClientFactory.clientConnectionLost( self, connector, unused_reason)
def test_handshake(self): """ The TLS handshake is performed when L{TLSMemoryBIOProtocol} is connected to a transport. """ clientFactory = ClientFactory() clientFactory.protocol = Protocol clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverFactory = ServerFactory() serverFactory.protocol = Protocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Only wait for the handshake to complete. Anything after that isn't # important here. return handshakeDeferred
def testGetPolicyFile(self): class PolicyRequest(Protocol): def __init__(self, deffered): self.done = deffered def connectionMade(self): request = "<policy-file-request/>%c" % (0, ) self.transport.write(request) def dataReceived(self, data): self.transport.loseConnection() self.done.callback(data) d = defer.Deferred() factory = ClientFactory() factory.protocol = lambda : PolicyRequest(d) port = self.listener._realPortNumber reactor.connectTCP('127.0.0.1', port, factory) def asserts(received): policy = ( '<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM ' '"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">' '<cross-domain-policy><allow-access-from domain="*" ' 'to-ports="*" /></cross-domain-policy>') self.assertEqual(policy, received) d.addCallback(asserts) return d
def test_writeSequence(self): """ Bytes written to L{TLSMemoryBIOProtocol} with C{writeSequence} are received by the protocol on the other side of the connection. """ bytes = "some bytes" class SimpleSendingProtocol(Protocol): def connectionMade(self): self.transport.writeSequence(list(bytes)) clientFactory = ClientFactory() clientFactory.protocol = SimpleSendingProtocol clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = AccumulatingProtocol(len(bytes)) serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the connection to end, then make sure the server received # the bytes sent by the client. def cbConnectionDone(ignored): self.assertEquals("".join(serverProtocol.received), bytes) connectionDeferred.addCallback(cbConnectionDone) return connectionDeferred
def test_disconnectWhileProducing(self): """ If C{loseConnection} is called while a producer is registered with the transport, the connection is closed after the producer is unregistered. """ reactor = self.buildReactor() # For some reason, pyobject/pygtk will not deliver the close # notification that should happen after the unregisterProducer call in # this test. The selectable is in the write notification set, but no # notification ever arrives. Probably for the same reason #5233 led # win32eventreactor to be broken. skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest("A pygobject/pygtk bug disables this functionality " "on Windows.") class Producer: def resumeProducing(self): log.msg("Producer.resumeProducing") self.listen(reactor, ServerFactory.forProtocol(Protocol)) finished = Deferred() finished.addErrback(log.err) finished.addCallback(lambda ign: reactor.stop()) class ClientProtocol(Protocol): """ Protocol to connect, register a producer, try to lose the connection, unregister the producer, and wait for the connection to actually be lost. """ def connectionMade(self): log.msg("ClientProtocol.connectionMade") self.transport.registerProducer(Producer(), False) self.transport.loseConnection() # Let the reactor tick over, in case synchronously calling # loseConnection and then unregisterProducer is the same as # synchronously calling unregisterProducer and then # loseConnection (as it is in several reactors). reactor.callLater(0, reactor.callLater, 0, self.unregister) def unregister(self): log.msg("ClientProtocol unregister") self.transport.unregisterProducer() # This should all be pretty quick. Fail the test # if we don't get a connectionLost event really # soon. reactor.callLater(1.0, finished.errback, Failure(Exception("Connection was not lost"))) def connectionLost(self, reason): log.msg("ClientProtocol.connectionLost") finished.callback(None) clientFactory = ClientFactory() clientFactory.protocol = ClientProtocol self.connect(reactor, clientFactory) self.runReactor(reactor)
def test_disorderlyShutdown(self): """ If a L{TLSMemoryBIOProtocol} loses its connection unexpectedly, this is reported to the application. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory = HandshakeCallbackContextFactory() wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) # Client speaks first, so the server can be dumb. serverProtocol = Protocol() connectionDeferred = loopbackAsync(serverProtocol, sslClientProtocol) # Now destroy the connection. serverProtocol.transport.loseConnection() # And when the connection completely dies, check the reason. def cbDisconnected(clientProtocol): clientProtocol.lostConnectionReason.trap(Error) clientConnectionLost.addCallback(cbDisconnected) return clientConnectionLost
def clientConnectionFailed(self, connector, reason): self.log.error( "Unable to connect to APN feedback server: {reason}", reason=reason, ) self.connected = False ClientFactory.clientConnectionFailed(self, connector, reason)
def new_protocol_tcp(self): """ Create a new client protocol connected to the server. :returns: a IRelayTestClient implementation """ server_factory = ServerFactory() server_factory.protocol = TransitConnection server_factory.transit = self._transit_server server_factory.log_requests = self.log_requests server_protocol = server_factory.buildProtocol(('127.0.0.1', 0)) @implementer(IRelayTestClient) class TransitClientProtocolTcp(Protocol): """ Speak the transit client protocol used by the tests over TCP """ _received = b"" connected = False # override Protocol callbacks def connectionMade(self): self.connected = True return Protocol.connectionMade(self) def connectionLost(self, reason): self.connected = False return Protocol.connectionLost(self, reason) def dataReceived(self, data): self._received = self._received + data # IRelayTestClient def send(self, data): self.transport.write(data) def disconnect(self): self.transport.loseConnection() def reset_received_data(self): self._received = b"" def get_received_data(self): return self._received client_factory = ClientFactory() client_factory.protocol = TransitClientProtocolTcp client_protocol = client_factory.buildProtocol(('127.0.0.1', 31337)) pump = iosim.connect( server_protocol, iosim.makeFakeServer(server_protocol), client_protocol, iosim.makeFakeClient(client_protocol), ) pump.flush() self._pumps.append(pump) return client_protocol
def getCachedConnection(self): """ Ask the L{conncache.ConnectionCache} for a connection to the endpoint created in L{setUp}. """ factory = ClientFactory() factory.protocol = lambda: self.protocol return self.cache.connectCached(self.endpoint, factory)
def main(): inventory = Inventory(100, 1) def protocol(): return MakerTraderClient(inventory) factory = ClientFactory() factory.protocol = protocol reactor.connectTCP("localhost", 8000, factory) reactor.run()
def clientConnectionLost(self, connector, reason): logger.info('lost connection: {}'.format(reason.getErrorMessage())) ClientFactory.clientConnectionLost(self, connector, reason) if self.reconnect: time.sleep(self.reconnect_delay) connector.connect() elif not self.protocols: if self.onFinish: self.onFinish.callback(None)
def clientConnectionFailed(self, connector, reason): logger.info('connection failed: %s', reason.getErrorMessage()) ClientFactory.clientConnectionFailed(self, connector, reason) if self.reconnect: time.sleep(self.reconnect_delay) connector.connect() elif not self.protocols: if self.onFinish: self.onFinish.callback(None)
def _create_client_factory(self, target_id): factory = ClientFactory() factory.protocol = OutgoingProtocol factory.target_id = target_id factory.add_connection = self.outgoing_connections.add factory.remove_connection = self.outgoing_connections.remove self._init_factory(factory) return factory
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.protocol = protoClass proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def connect(self, host, port): self._connection_timeout = self.timeout self._stack_conn = _Connection() self._stack_conn.attach(self) self._stack_conn.connect_cb = Callback() factory = ClientFactory() factory.protocol = lambda: self._stack_conn factory.clientConnectionFailed = self.clientConnectionFailed self._connect_to_reactor(host, port, factory, self._connection_timeout) yield self._stack_conn.connect_cb
def buildProtocol(self, address): """ Overriden method to distinguish between the two protocols. """ if address.port == 8888: self.protocol = DirectoryProtocol self.dirProto = ClientFactory.buildProtocol(self, address) return self.dirProto else: self.protocol = PeerProtocol return ClientFactory.buildProtocol(self, address)
def test_doStop(self): """ L{_WrappingFactory.doStop} passes through to the wrapped factory's C{doStop} method, allowing application-specific cleanup and logging. """ factory = ClientFactory() factory.numPorts = 3 wf = endpoints._WrappingFactory(factory) wf.doStop() self.assertEqual(2, factory.numPorts)
def connectionMade(self): self.buffer = [] self.client = None cli_factory = ClientFactory() cli_factory.protocol = SyncplayProxyClientProtocol cli_factory.server = self host_name, host_port = self._factory.host_name, self._factory.host_port reactor.connectTCP(host_name, host_port, cli_factory)
def sbRequestAccepted((host, port, key)): LogEvent(INFO, self.ident) self.key = key self.reply = 0 factory = ClientFactory() factory.buildProtocol = lambda addr: self self.msncon.connectors.append( reactor.connectTCP(host, port, factory, bindAddress=(MSNConnection.BINDADDRESS, 0)))
def makeProto(self, *a, **kw): protoClass = kw.pop('_protoClass', self.protocol) fac = ClientFactory(*a, **kw) fac.protocol = protoClass def raise_(ex): raise ex fac.bobConnectionFailed = lambda reason: raise_(reason) proto = fac.buildProtocol(None) transport = proto_helpers.StringTransport() transport.abortConnection = lambda: None proto.makeConnection(transport) return fac, proto
def clientConnectionFailed(self, connector, reason): logging.info('Connection failed') ClientFactory.clientConnectionFailed(self, connector, reason) #If first connection was failed - try to start server if not self.reconnect: #Start, reconnect try: subprocess.Popen(['python', 'server.py']).wait() except Exception, err: logging.exception('Error starting server: %s', err) time.sleep(3) do_connect(self.listener, True)
def test_loseConnectionAfterHandshake(self): """ L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and shuts down the underlying connection. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol(clientConnectionLost)) clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory(clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = Protocol() serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory(serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the handshake before dropping the connection. def cbHandshake(ignored): serverProtocol.transport.loseConnection() # Now wait for the client to notice. return clientConnectionLost handshakeDeferred.addCallback(cbHandshake) # Wait for the connection to end, then make sure the client was # notified of a handshake failure. def cbConnectionDone(clientProtocol): clientProtocol.lostConnectionReason.trap(ConnectionDone) # The server should have closed its underlying transport, in # addition to whatever it did to shut down the TLS layer. self.assertTrue(serverProtocol.transport.q.disconnect) # The client should also have closed its underlying transport once # it saw the server shut down the TLS layer, so as to avoid relying # on the server to close the underlying connection. self.assertTrue(clientProtocol.transport.q.disconnect) handshakeDeferred.addCallback(cbConnectionDone) return handshakeDeferred
def clientConnectionFailed(self, connector, reason): logger.info('connection failed: {}'.format(reason)) ClientFactory.clientConnectionFailed(self, connector, reason) if self.reconnect: reactor.callFromThread(time.sleep, self.reconnect_delay) connector.connect() else: if self.standalone: try: reactor.callFromThread(reactor.stop) except ReactorNotRunning: pass
def main(): serverFactory = ServerFactory() serverFactory.protocol = myHost() reactor.listenTCP(8000, serverFactory) reactor.run() host = raw_input("Enter chat screen name.\n") clientFactory = ClientFactory() clientFactory.protocol = myFactory() reactor.listenTCP(8000, serverFactory) reactor.run()
def _createClientFactory(self, tcpip=None, tcpport=None): import freetime.entity.config as ftconfig if ftconfig.global_config.get('is_h5', 0): # from autobahn.twisted.websocket import WebSocketClientFactory # factory = WebSocketClientFactory("ws://" + tcpip + ":" + str(tcpport), debug=True) factory = H5WebSocketClientFactory("ws://" + tcpip + ":" + str(tcpport), debug=True) factory.protocol = self._makeRoboProtocloWs return factory else: from twisted.internet.protocol import ClientFactory factory = ClientFactory() factory.protocol = self._makeRoboProtoclo return factory
def connectReply(self, host, port, key, sessionID): LogEvent(INFO, self.ident) self.ready = False self.key = key self.sessionID = sessionID self.reply = 1 factory = ClientFactory() factory.buildProtocol = lambda addr: self self.msncon.connectors.append( reactor.connectTCP(host, port, factory, bindAddress=(MSNConnection.BINDADDRESS, 0)))
def connect(self, host, port): self._stack_conn = _Connection() self._stack_conn.attach(self) self._stack_conn.connect_cb = Callback() factory = ClientFactory() factory.protocol = lambda: self._stack_conn factory.clientConnectionFailed = self.clientConnectionFailed if self.ssl_options is not None: reactor.connectSSL(host, port, factory, SSLContextFactory(self.ssl_options)) else: reactor.connectTCP(host, port, factory) yield self._stack_conn.connect_cb
def test_loseConnectionAfterHandshake(self): """ L{TLSMemoryBIOProtocol.loseConnection} sends a TLS close alert and shuts down the underlying connection. """ clientConnectionLost = Deferred() clientFactory = ClientFactory() clientFactory.protocol = ( lambda: ConnectionLostNotifyingProtocol( clientConnectionLost)) clientContextFactory, handshakeDeferred = ( HandshakeCallbackContextFactory.factoryAndDeferred()) wrapperFactory = TLSMemoryBIOFactory( clientContextFactory, True, clientFactory) sslClientProtocol = wrapperFactory.buildProtocol(None) serverProtocol = Protocol() serverFactory = ServerFactory() serverFactory.protocol = lambda: serverProtocol serverContextFactory = DefaultOpenSSLContextFactory(certPath, certPath) wrapperFactory = TLSMemoryBIOFactory( serverContextFactory, False, serverFactory) sslServerProtocol = wrapperFactory.buildProtocol(None) connectionDeferred = loopbackAsync(sslServerProtocol, sslClientProtocol) # Wait for the handshake before dropping the connection. def cbHandshake(ignored): serverProtocol.transport.loseConnection() # Now wait for the client to notice. return clientConnectionLost handshakeDeferred.addCallback(cbHandshake) # Wait for the connection to end, then make sure the client was # notified of a handshake failure. def cbConnectionDone(clientProtocol): clientProtocol.lostConnectionReason.trap(ConnectionDone) # The server should have closed its underlying transport, in # addition to whatever it did to shut down the TLS layer. self.assertTrue(serverProtocol.transport.q.disconnect) # The client should also have closed its underlying transport once # it saw the server shut down the TLS layer, so as to avoid relying # on the server to close the underlying connection. self.assertTrue(clientProtocol.transport.q.disconnect) handshakeDeferred.addCallback(cbConnectionDone) return handshakeDeferred
def open(self): """open the connection to the lircd socket""" def gotProtocol(result): """now we have a connection""" self.protocol = result self.protocol.wrapper = self print 'got lirc protocol' def gotNoProtocol(result): """something went wrong""" print "got no connection to lirc: %s" % result point = UNIXClientEndpoint(reactor, self.irwSocket, timeout=2) factory = ClientFactory() factory.protocol = LircProtocol point.connect(factory).addCallback(gotProtocol).addErrback(gotNoProtocol)
def test_badContext(self): """ If the context factory passed to L{ITCPTransport.startTLS} raises an exception from its C{getContext} method, that exception is raised by L{ITCPTransport.startTLS}. """ reactor = self.buildReactor() brokenFactory = BrokenContextFactory() results = [] serverFactory = ServerFactory() serverFactory.protocol = Protocol port = reactor.listenTCP(0, serverFactory, interface=self.interface) endpoint = self.endpoints.client(reactor, port.getHost()) clientFactory = ClientFactory() clientFactory.protocol = Protocol connectDeferred = endpoint.connect(clientFactory) def connected(protocol): if not ITLSTransport.providedBy(protocol.transport): results.append("skip") else: results.append( self.assertRaises(ValueError, protocol.transport.startTLS, brokenFactory)) def connectFailed(failure): results.append(failure) def whenRun(): connectDeferred.addCallback(connected) connectDeferred.addErrback(connectFailed) connectDeferred.addBoth(lambda ign: reactor.stop()) needsRunningReactor(reactor, whenRun) self.runReactor(reactor) self.assertEqual(len(results), 1, "more than one callback result: %s" % (results, )) if isinstance(results[0], Failure): # self.fail(Failure) results[0].raiseException() if results[0] == "skip": raise SkipTest("Reactor does not support ITLSTransport") self.assertEqual(BrokenContextFactory.message, str(results[0]))
def main(): inventory = Inventory(100) def protocol(): RTC_instance = RandomTraderClient(inventory) # Read in file #RTC_instance.readCSVorder() # Return RTC instance after reading csv file return RTC_instance factory = ClientFactory() factory.protocol = protocol reactor.connectTCP("localhost", 8000, factory) reactor.run()
def test_stopStartReading(self): """ This test verifies transport socket read state after multiple pause/resumeProducing calls. """ sf = ServerFactory() reactor = sf.reactor = self.buildReactor() skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest("This test is broken on gtk/glib under Windows.") sf.protocol = StopStartReadingProtocol sf.ready = Deferred() sf.stop = Deferred() p = reactor.listenTCP(0, sf) port = p.getHost().port def proceed(protos, port): """ Send several IOCPReactor's buffers' worth of data. """ self.assertTrue(protos[0]) self.assertTrue(protos[1]) protos = protos[0][1], protos[1][1] protos[0].transport.write('x' * (2 * 4096) + 'y' * (2 * 4096)) return (sf.stop.addCallback( cleanup, protos, port).addCallback(lambda ign: reactor.stop())) def cleanup(data, protos, port): """ Make sure IOCPReactor didn't start several WSARecv operations that clobbered each other's results. """ self.assertEquals(data, 'x' * (2 * 4096) + 'y' * (2 * 4096), 'did not get the right data') return DeferredList([ maybeDeferred(protos[0].transport.loseConnection), maybeDeferred(protos[1].transport.loseConnection), maybeDeferred(port.stopListening) ]) cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port) cf = ClientFactory() cf.protocol = Protocol d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p) self.runReactor(reactor) return d
def main(): import optparse parser = optparse.OptionParser(__doc__.strip()) parser.add_option('--host', action='store', default='localhost', help="Host to connect to.") parser.add_option('--port', action='store', type='int', default=5970, help="Port to connect to.") opts, args = parser.parse_args() factory = ClientFactory() factory.protocol = ClientProtocol reactor.connectTCP(opts.host, opts.port, factory) reactor.run()
def test_interface(self): """ The C{connect} method returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = self.connect(reactor, ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
def test_interface(self): """ L{IReactorTCP.connectTCP} returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = reactor.connectTCP("127.0.0.1", 1234, ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
def test_interface(self): """ L{IReactorUNIX.connectUNIX} returns an object providing L{IConnector}. """ reactor = self.buildReactor() connector = reactor.connectUNIX(self.mktemp(), ClientFactory()) self.assertTrue(verifyObject(IConnector, connector))
def buildProtocol(self, address): logger.vdebug( "Building protocol in StarboundClientFactory to address %s", address) protocol = ClientFactory.buildProtocol(self, address) protocol.server_protocol = self.server_protocol return protocol
def __init__(self, config, app=None): super().__init__(config, app) self.factory = ClientFactory() self.factory.config = config self.factory.protocol = TwistedHandler self.factory.protocol_factory = self.protocol_factory
def buildProtocol(self, addr): """Provision protocol with the dedicated logger """ proto = ClientFactory.buildProtocol(self, addr) proto.log = self.log return proto