Created
August 13, 2016 20:34
-
-
Save tehasdf/20affda6b7fd703adf0e905324fc55f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from twisted.protocols.basic import LineOnlyReceiver | |
from twisted.internet.defer import Deferred | |
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol | |
class MyLineReceiver(LineOnlyReceiver): | |
def __init__(self, to_send): | |
self._to_send = to_send | |
self.deferred = Deferred() | |
self._received = [] | |
def connectionMade(self): | |
self.sendLine(self._to_send) | |
def lineReceived(self, line): | |
self._received.append(line) | |
if 'END' in line: | |
self.transport.loseConnection() | |
def connectionLost(self, reason): | |
# TODO: check reason and maybe errback | |
self.deferred.callback(self._received) | |
def do_request(addr, request): | |
ep = TCP4ClientEndpoint(reactor, addr, 8080) | |
return (connectProtocol(ep, MyLineReceiver(request)) | |
.addCallback(lambda proto: proto.deferred) | |
) | |
@inlineCallbacks | |
def foo(): | |
response = yield do_request('127.0.0.1', 'here is a line') | |
assert response == ['OK response here', 'another line', 'END'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment