'Make a wrapper function for the ssync_sender.Sender.connect() method
that will in turn wrap the HTTConnection.send() and the
Sender.readline() so that ssync protocol messages can be captured.'

def make_connect_wrapper(self, sender):

    orig_connect = sender.connect
    trace = dict(messages=[])
    def add_trace(type, msg):
        if msg.strip():
            trace['messages'].append((type, msg.strip()))
    def make_send_wrapper(send):
        def wrapped_send(msg):
            _msg = msg.split('\r\n', 1)[1]
            _msg = _msg.rsplit('\r\n', 1)[0]
            add_trace('tx', _msg)
            send(msg)
        return wrapped_send
    def make_readline_wrapper(readline):
        def wrapped_readline():
            data = readline()
            add_trace('rx', data)
            bytes_read = trace.setdefault('readline_bytes', 0)
            trace['readline_bytes'] = (bytes_read + len(data))
            return data
        return wrapped_readline
    def wrapped_connect():
        orig_connect()
        sender.connection.send = make_send_wrapper(sender.connection.send)
        sender.readline = make_readline_wrapper(sender.readline)
    return (wrapped_connect, trace)
