The client performs a HTTP persistent connection and watches changes in response and the server prints chunk as data to response.
160793
function createStreamTransport(req, res) {
    // A transport object.
    var self = createBaseTransport(req, res);
    // Any error on request-response should propagate to transport.
    req.on("error", function(error) {
        self.emit("error", error);
    });
    res.on("error", function(error) {
        self.emit("error", error);
    });
    // When the underlying connection was terminated abnormally.
    res.on("close", function() {
        self.emit("close");
    });
    // When the complete response has been sent.
    res.on("finish", function() {
        self.emit("close");
    });

    // The response body should be formatted in the [event stream
    // format](http://www.w3.org/TR/eventsource/#parsing-an-event-stream).
    self.write = function(data) {
        // `data` should be either a `Buffer` or a string.
        if (typeof data === "string") {
            // A text message should be prefixed with `1`.
            data = "1" + data;
        } else {
            // A binary message should be encoded in Base64 and prefixed with
            // `2`.
            data = "2" + data.toString("base64");
        }
        // According to the format, data should be broken up by `\r`, `\n`, or
        // `\r\n`.
        var payload = data.split(/\r\n|[\r\n]/).map(function(line) {
            // Each line should be prefixed with 'data: ' and postfixed with
            // `\n`.
            return "data: " + line + "\n";
        })
        // Prints `\n` as the last character of a message.
        .join("") + "\n";
        // Writes it to response with `utf-8` encoding.
        res.write(payload, "utf-8");
    };
    // Ends the response. Accordingly, `res`'s `finish` event will be fired.
    self.close = function() {
        res.end();
        return this;
    };

    // The content-type headers should be `text/event-stream` for Server-Sent
    // Events and `text/plain` for others. Also the response should be encoded in `utf-8`.
    res.setHeader("content-type", "text/" + 
        // If it's Server-Sent Events, `sse` param is `true`.
        (req.params.sse === "true" ? "event-stream" : "plain") + "; charset=utf-8");
    // The padding is required, which makes the client-side transport on old
    // browsers be aware of change of the response. It should be greater
    // than 1KB, be composed of white space character and end with `\n`.
    var text2KB = Array(2048).join(" ");
    // Some host objects which are used to perform streaming transport can't or
    // don't allow to read response headers as well as write request headers.
    // That's why we uses the first message as a handshake output. The handshake
    // result should be formatted in URI. And transport id should be added as
    // `id` param.
    var uri = url.format({query: {id: self.id}});
    // Likewise some host objects in old browsers, junk data is needed to make
    // themselves be aware of change of response. Prints the padding and the
    // first message following `text/event-stream` with `utf-8` encoding.
    res.write(text2KB + "\ndata: " + uri + "\n\n", "utf-8");
    return self;    
}
895893
public static OutputStream put(HttpNode resource) throws IOException {
        Request put;
        HttpConnection connection;

        put = new Request("PUT", resource);
        put.addRequestHeader(Header.TRANSFER_ENCODING, HttpConnection.CHUNK_CODING);
        connection = put.open(null);
        return new ChunkedOutputStream(connection.getOutputStream()) {
            private boolean closed = false;
            @Override
            public void close() throws IOException {
                Response reponse;
                int code;

                if (closed) {
                    return;
                }
                closed = true;
                super.close();
                reponse = put.finish(connection);
                code = reponse.getStatusLine().code;
                if (code != StatusCode.OK && code != StatusCode.NO_CONTENT && code != StatusCode.CREATED) {
                    throw StatusException.forResponse(resource, reponse);
                }
            }
        };
    }
1128425
def __ProcessResponse(self, response):
        """"""
        if response.status_code not in self._ACCEPTABLE_STATUSES:
            # We distinguish errors that mean we made a mistake in setting
            # up the transfer versus something we should attempt again.
            if response.status_code in (http_client.FORBIDDEN,
                                        http_client.NOT_FOUND):
                raise exceptions.HttpError.FromResponse(response)
            else:
                raise exceptions.TransferRetryError(response.content)
        if response.status_code in (http_client.OK,
                                    http_client.PARTIAL_CONTENT):
            try:
                self.stream.write(six.ensure_binary(response.content))
            except TypeError:
                self.stream.write(six.ensure_text(response.content))
            self.__progress += response.length
            if response.info and 'content-encoding' in response.info:
                # TODO(craigcitro): Handle the case where this changes over a
                # download.
                self.__encoding = response.info['content-encoding']
        elif response.status_code == http_client.NO_CONTENT:
            # It's important to write something to the stream for the case
            # of a 0-byte download to a file, as otherwise python won't
            # create the file.
            self.stream.write('')
        return response
191623
def watch(callback, url=default_sock_url):
    
    sock, hostname = connect(url)
    request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname
    request = request.encode('utf-8')

    with closing(sock):
        sock.sendall(request)
        header, payload = read_http_header(sock)
        status, reason = header_status(header)
        if status != HTTP_OK:
            raise DockermonError('bad HTTP status: %s %s' % (status, reason))

        # Messages are \r\n<size in hex><JSON payload>\r\n
        buf = [payload]
        while True:
            chunk = sock.recv(bufsize)
            if not chunk:
                raise EOFError('socket closed')
            buf.append(chunk.decode('utf-8'))
            data = ''.join(buf)
            i = data.find('\r\n')
            if i == -1:
                continue

            size = int(data[:i], 16)
            start = i + 2  # Skip initial \r\n

            if len(data) < start + size + 2:
                continue
            payload = data[start:start+size]
            callback(json.loads(payload))
            buf = [data[start+size+2:]]
1033562
def http_log_graph(self, stream):
        '''  '''
        print 'Entering http_log_graph...'
        for row in list(stream):

            # Skip '-' hosts
            if (row['id.orig_h'] == '-'):
                continue

            # Add the originating host
            self.add_node(row['id.orig_h'], row['id.orig_h'], ['host', 'origin'])

            # Add the response host and reponse ip
            self.add_node(row['host'], row['host'], ['host'])
            self.add_node(row['id.resp_h'], row['id.resp_h'], ['host'])

            # Add the http request relationships
            self.add_rel(row['id.orig_h'], row['host'], 'http_request')
            self.add_rel(row['host'], row['id.resp_h'], 'A')
1260979
function(base_url, callback, cors) {
    var recv = new XhrReceiver(base_url + '/chunking_test', {cors: cors});
    var result = 0;
    recv.onmessage = function(e) {
        // Now a cool hack: we can stop receiving after we got at least
        // one chunk, contains some data, but not everyting.
        var l = e.responsetext.split('h\n').length;
        if(e.readystate === 3 && l > 0 && l < 6 ) {
            result = l;
            recv.abort();
        }
    };
    recv.onclose = function(e) {
        recv = recv.onmessage = recv.onclose = null;
        utils.log('Chunking test: ' + (result ? 'passed' : 'failed')
                  + ' (' + result + ' chunk received)');
        callback(!!result);
    };
}
1288929
function onData( chunk ) {
		self.res.bytes += chunk.length;
		body += chunk.toString();
	}
1345914
def stream_upload(self, data, callback):
        
        while True:
            chunk = data.read(self.config.connection.data_block_size)
            if not chunk:
                break
            if callback and callable(callback):
                callback(chunk, response=None)
            yield chunk
653770
def _on_new_data_received(self, data: bytes):
        
        if data == b' ':
            # Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's send it back.
            self.loop.call_soon_threadsafe(self.connection.send_raw_data, b' ')
            return

        xml_element = BeautifulSoup(data.decode(), features='xml')
        xml_element = next(iter(xml_element)) if len(xml_element) > 0 else xml_element

        # choose the handler based on the XML tag name

        if xml_element.name == "k":
            self._handle_received_k_element(xml_element)
        if xml_element.name == "iq":
            self._handle_received_iq_element(xml_element)
        elif xml_element.name == "message":
            self._handle_xmpp_message(xml_element)
        elif xml_element.name == 'stc':
            self.callback.on_captcha_received(login.CaptchaElement(xml_element))
1029144
void fakeResponse(
        StatusLine statusline, 
        HeaderGroup responseheaders,
        HttpConnection conn,
        InputStream responseStream
    ) {
        // set used so that the response can be read
        this.used = true;
        this.statusLine = statusline;
        this.responseHeaders = responseheaders;
        this.responseConnection = conn;
        this.responseBody = null;
        this.responseStream = responseStream;
    }
157709
private void onDataRead(int streamId, ByteBuf data, int padding, boolean endOfStream) {
    flowControlPing().onDataRead(data.readableBytes(), padding);
    NettyClientStream.TransportState stream = clientStream(requireHttp2Stream(streamId));
    stream.transportDataReceived(data, endOfStream);
    if (keepAliveManager != null) {
      keepAliveManager.onDataReceived();
    }
  }
34931
def build_response(
        self, request, response, from_cache=False, cacheable_methods=None
    ):
        
        cacheable = cacheable_methods or self.cacheable_methods
        if not from_cache and request.method in cacheable:
            # Check for any heuristics that might update headers
            # before trying to cache.
            if self.heuristic:
                response = self.heuristic.apply(response)

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response

            # We always cache the 301 responses
            elif response.status == 301:
                self.controller.cache_response(request, response)
            else:
                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response, request, response
                    ),
                )
                if response.chunked:
                    super_update_chunk_length = response._update_chunk_length

                    def _update_chunk_length(self):
                        super_update_chunk_length()
                        if self.chunk_left == 0:
                            self._fp._close()

                    response._update_chunk_length = types.MethodType(
                        _update_chunk_length, response
                    )

        resp = super(CacheControlAdapter, self).build_response(request, response)

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp
871331
public void handleTrace(HttpRequest request,
                            HttpResponse response)
        throws IOException
    {
        boolean trace=getHttpContext().getHttpServer().getTrace();
        
        // Handle TRACE by returning request header
        response.setField(HttpFields.__ContentType,
                          HttpFields.__MessageHttp);
        if (trace)
        {
            OutputStream out = response.getOutputStream();
            ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
            writer.write(request.toString());
            writer.flush();
            response.setIntField(HttpFields.__ContentLength,writer.size());
            writer.writeTo(out);
            out.flush();
        }
        request.setHandled(true);
    }
702381
function (event) {
                // Send the HttpResponseHeaders event if it hasn't been sent already.
                if (!sentHeaders) {
                    observer.next(partialFromXhr());
                    sentHeaders = true;
                }
                // Start building the download progress event to deliver on the response
                // event stream.
                var progressEvent = {
                    type: HttpEventType.DownloadProgress,
                    loaded: event.loaded,
                };
                // Set the total number of bytes in the event if it's available.
                if (event.lengthComputable) {
                    progressEvent.total = event.total;
                }
                // If the request was for text content and a partial response is
                // available on XMLHttpRequest, include it in the progress event
                // to allow for streaming reads.
                if (req.responseType === 'text' && !!xhr.responseText) {
                    progressEvent.partialText = xhr.responseText;
                }
                // Finally, fire the event.
                observer.next(progressEvent);
            }
224085
def on_connect(self, connection):
        ""
        self._stream = connection._reader
        self._buffer = SocketBuffer(self._stream, self._read_size)
        if connection.decode_responses:
            self.encoding = connection.encoding
7603
def on_headers(self, response, exc=None):
        ''''''

        if response.status_code == 101:
            connection = response.connection
            request = response.request
            handler = request.websocket_handler
            if not handler:
                handler = WS()
            parser = request.client.frame_parser(kind=1)
            consumer = partial(WebSocketClient.create,
                               response, handler, parser)
            connection.upgrade(consumer)
            response.event('post_request').fire()
            websocket = connection.current_consumer()
            response.request_again = lambda r: websocket
1191047
def do_GET(self):
        
        self.do_initial_operations()
        coap_response = self.client.get(self.coap_uri.path)
        self.client.stop()
        logger.info("Server response: %s", coap_response.pretty_print())
        self.set_http_response(coap_response)