--- REQUEST PACKET ---
339725
public void sendRequestPacket(String nodeID, Context ctx) {
		FastBuildTree msg = new FastBuildTree(11);

		// Add basic properties (version, sender's nodeID, etc.)
		msg.putUnsafe("ver", PROTOCOL_VERSION);
		msg.putUnsafe("sender", this.nodeID);
		msg.putUnsafe("id", ctx.id);
		msg.putUnsafe("action", ctx.name);

		// Add params and meta
		if (ctx.params != null) {
			msg.putUnsafe("params", ctx.params.asObject());
			Tree meta = ctx.params.getMeta(false);
			if (meta != null && !meta.isEmpty()) {
				msg.putUnsafe("meta", meta.asObject());
			}
		}

		// Timeout
		if (ctx.opts != null && ctx.opts.timeout > 0) {
			msg.putUnsafe("timeout", ctx.opts.timeout);
		}

		// Call level
		msg.putUnsafe("level", ctx.level);

		// Parent ID
		if (ctx.parentID != null) {
			msg.putUnsafe("parentID", ctx.parentID);
		}

		// Request ID
		msg.putUnsafe("requestID", ctx.requestID);

		// Stream packet counter (default is "0" = packet isn't streamed)
		if (ctx.stream != null) {

			// Streaming in progress
			msg.putUnsafe("stream", true);

			// First sequence
			msg.putUnsafe("seq", 0);
		}

		// Send message
		publish(Transporter.PACKET_REQUEST, nodeID, msg);
	}
582564
function(packet) {
    if (packet && packet.peek() === 0xff) {
      //can receive unexpected error packet from server/proxy
      //to inform that connection is closed (usually by timeout)
      let err = packet.readError(info);
      if (
        err.fatal &&
        (_status !== Status.CLOSING && _status !== Status.CLOSED)
      ) {
        this.emit('error', err);
        this.end();
      }
    } else if (_status !== Status.CLOSING && _status !== Status.CLOSED) {
      this.emit(
        'error',
        Errors.createError(
          'receiving packet from server without active commands\n' +
            'conn:' +
            (info.threadId ? info.threadId : -1) +
            '(' +
            packet.pos +
            ',' +
            packet.end +
            ')\n' +
            Utils.log(opts, packet.buf, packet.pos, packet.end),
          true,
          info,
          '08S01',
          Errors.ER_UNEXPECTED_PACKET
        )
      );
      this.destroy();
    }
  }
237559
def incoming(self, packet):
        
        # This might be done prettier ;-)
        console_text = packet.data.decode('UTF-8')

        self.receivedChar.call(console_text)
233274
@Override
	public boolean packetReceived(AbstractPacket packet)
    {
        AbstractQueryPacket query = (AbstractQueryPacket)packet;
    	AbstractResponsePacket response = null;
    	
    	// Process packet
        try
        {
            try
            {
                response = process(query);
            }
            catch (JMSException e)
            {
            	log.debug("#"+id+" process() failed with "+e.toString());
                response = new ErrorResponse(e);
            }
        }
        catch (Exception e)
        {
            log.error("#"+id+" Cannot process command",e);
        }
        
        // Send response
        if (response != null && query.isResponseExpected())
        {        	
            // Map endpoint id on response
            response.setEndpointId(query.getEndpointId());
            
	        try
	        {   
	            if (traceEnabled)
	                log.trace("#"+id+" Sending "+response);
	            transport.send(response);
	        }
	        catch (Exception e)
	        {
	            log.warn("#"+id+" Cannot send response to client : "+e.toString());
	            transport.close();
	        }
        }
        
        return localConnection != null; // Connection still valid ?
    }
1220544
def packet(self):
        """"""
        if not self.finished:
            self.finished = 1
            for question in self.questions:
                self.write_question(question)
            for answer, time in self.answers:
                self.write_record(answer, time)
            for authority in self.authorities:
                self.write_record(authority, 0)
            for additional in self.additionals:
                self.write_record(additional, 0)

            self.insert_short(0, len(self.additionals))
            self.insert_short(0, len(self.authorities))
            self.insert_short(0, len(self.answers))
            self.insert_short(0, len(self.questions))
            self.insert_short(0, self.flags)
            if self.multicast:
                self.insert_short(0, 0)
            else:
                self.insert_short(0, self.id)
        return b''.join(self.data)
723243
function _request(url, opt) {
      opt = opt || {};
      opt.method = (opt.method || 'GET').toUpperCase();
      opt.headers = opt.headers || {};
      if (matchUrl(url) && matchMethod(opt.method)) {
        const result = extend(true, {}, mockResult);
        const response = {
          status: result.status,
          statusCode: result.status,
          headers: result.headers,
          size: result.responseSize,
          aborted: false,
          rt: 1,
          keepAliveSocket: result.keepAliveSocket || false,
        };

        httpclient.emit('response', {
          error: null,
          ctx: opt.ctx,
          req: {
            url,
            options: opt,
            size: result.requestSize,
          },
          res: response,
        });
        if (opt.dataType === 'json') {
          try {
            result.data = JSON.parse(result.data);
          } catch (err) {
            err.name = 'JSONResponseFormatError';
            throw err;
          }
        } else if (opt.dataType === 'text') {
          result.data = result.data.toString();
        }
        return Promise.resolve(result);
      }
      return rawRequest.call(httpclient, url, opt);
    }
1207831
private void requestBlock() {
    next = ByteBuffer.allocate(blockSizeBytes);
    long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();
    pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);
  }
106579
@Override
  protected void initRequest()
  {
    super.initRequest();
    
    _state = _state.toActive();
    
    // HttpBufferStore httpBuffer = getHttpBufferStore();
    HttpBufferStore bufferStore = getHttpBufferStore();

    _method.clear();
    _methodString = null;
    _protocol.clear();

    _uriLength = 0;
    if (bufferStore == null) {
      // server/05h8
      _uri = getSmallUriBuffer(); // httpBuffer.getUriBuffer();
      
      _headerBuffer = getSmallHeaderBuffer(); // httpBuffer.getHeaderBuffer();
      _headerKeys = getSmallHeaderKeys();     // httpBuffer.getHeaderKeys();
      _headerValues = getSmallHeaderValues(); // httpBuffer.getHeaderValues();
    }

    _uriHost.clear();
    _host = null;
    _keepalive = KeepaliveState.INIT;

    _headerSize = 0;
    _headerLength = 0;
    
    _inOffset = 0;
    _isChunkedIn = false;
    _isFirst = true;
  }
150295
private void getRequest(int function, BytesOutputStream out) throws IOException {
        int byteCount;
        byte inpBuf[] = new byte[256];
        try {
            if ((function & 0x80) == 0) {
                switch (function) {
                    case Modbus.READ_EXCEPTION_STATUS:
                    case Modbus.READ_COMM_EVENT_COUNTER:
                    case Modbus.READ_COMM_EVENT_LOG:
                    case Modbus.REPORT_SLAVE_ID:
                        readRequestData(0, out);
                        break;

                    case Modbus.READ_FIFO_QUEUE:
                        readRequestData(2, out);
                        break;

                    case Modbus.READ_MEI:
                        readRequestData(3, out);
                        break;

                    case Modbus.READ_COILS:
                    case Modbus.READ_INPUT_DISCRETES:
                    case Modbus.READ_MULTIPLE_REGISTERS:
                    case Modbus.READ_INPUT_REGISTERS:
                    case Modbus.WRITE_COIL:
                    case Modbus.WRITE_SINGLE_REGISTER:
                        readRequestData(4, out);
                        break;
                    case Modbus.MASK_WRITE_REGISTER:
                        readRequestData(6, out);
                        break;

                    case Modbus.READ_FILE_RECORD:
                    case Modbus.WRITE_FILE_RECORD:
                        byteCount = readByte();
                        out.write(byteCount);
                        readRequestData(byteCount, out);
                        break;

                    case Modbus.WRITE_MULTIPLE_COILS:
                    case Modbus.WRITE_MULTIPLE_REGISTERS:
                        readBytes(inpBuf, 4);
                        out.write(inpBuf, 0, 4);
                        byteCount = readByte();
                        out.write(byteCount);
                        readRequestData(byteCount, out);
                        break;

                    case Modbus.READ_WRITE_MULTIPLE:
                        readRequestData(8, out);
                        byteCount = readByte();
                        out.write(byteCount);
                        readRequestData(byteCount, out);
                        break;

                    default:
                        throw new IOException(String.format("getResponse unrecognised function code [%s]", function));
                }
            }
        }
        catch (IOException e) {
            throw new IOException("getResponse serial port exception");
        }
    }
11215
function makeRequest(title, cacheHitExpected, next) {
  var start = Date.now();

  request({
    url: 'http://localhost:1337/',
    encoding: null
  }, function(err, data, body) {
    var time = Date.now() - start;

    var receivedImage = new Buffer(body, 'binary');

    console.log(title);
    console.log('  status:', data.statusCode);
    console.log('  sent image length:', IMAGE.length);
    console.log('  received image length  :', receivedImage.length);
    console.log('  time  :', time);
    
    common.verify(function() {
      common.shouldEquals(IMAGE, receivedImage);
    });

    console.log();

    next();
  });
}
1183829
@Override
    public Packet getPacket(final Protocol p) throws IOException, PacketParseException {
        if (this.protocol == p) {
            return this;
        }

        final Packet child = getNextPacket();
        if (child != null && child.getProtocol() == p) {
            return child;
        }

        if (child == null) {
            return checkParent(p);
        }

        return child.getPacket(p);
    }
502908
protected void initRequest()
  {
    _hostHeader = null;
    _xForwardedHostHeader = null;
    _expect100Continue = false;

    _cookies.clear();

    _contentLengthIn = -1;

    _hasReadStream = false;

    _readEncoding = null;

    //_request = request;
    //_requestFacade = getHttp().createFacade(this);
    
    _startTime = -1;
    _expireTime = -1;
    
    _isUpgrade = false;
    
    _statusCode = 200;
    _statusMessage = "OK";

    _headerKeysOut.clear();
    _headerValuesOut.clear();
    
    _contentTypeOut = null;
    _contentEncodingOut = null;
    _contentLengthOut = -1;

    _footerKeys.clear();
    _footerValues.clear();

    out().start();

    _isHeaderWritten = false;

    _isClosed = false;
    //_serverHeader = http().serverHeader();
    
    _isKeepalive = true;
  }
687936
private int request (String encoded) throws IOException {
    refreshSignature();
    HttpPost httpPost = new HttpPost(targetURI);
    httpPost.setHeader("Content-type", "application/vnd.microsoft.servicebus.json");
    httpPost.setHeader("Authorization", signature);
    httpPost.setHeader("Host", namespaceName + ".servicebus.windows.net ");

    StringEntity entity = new StringEntity(encoded);
    httpPost.setEntity(entity);

    HttpResponse response = httpclient.execute(httpPost);
    StatusLine status = response.getStatusLine();
    HttpEntity entity2 = response.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);

    int returnCode = status.getStatusCode();
    if (returnCode != HttpStatus.SC_CREATED) {
      LOG.error (new IOException(status.getReasonPhrase()).toString());
      throw new IOException(status.getReasonPhrase());
    }

    return returnCode;
  }
1154439
function request(method, address, body, options) {
  let timeout = null;
  return new Promise((resolve, reject) => {
    try {
      const opts = _.merge({}, this.options, options, url.parse(address), {
        method,
      });

      // handle optional timeout
      if (typeof opts.timeout === 'number') {
        setTimeout(() => {
          reject(new Error(`${method} "${address}" timed out`));
          timeout = null;
        }, Math.floor(opts.timeout));
      }

      // create some request middleware to potentially
      // add headers ahead of time for auth or set cors, etc.
      const before =
        typeof opts.before === 'function'
          ? opts.before.call(this.context, method, address, opts)
          : () => null;

      const proto = opts.protocol === 'https:' ? https : http;

      return Promise.resolve(before)
        .then(() => {
          clearTimeout(timeout);

          const req = proto.request(opts, res => {
            let data = '';
            res
              .on('data', d => {
                data += d;
              })
              .on('error', error => {
                clearTimeout(timeout);
                reject(error);
              })
              .on('end', () => {
                clearTimeout(timeout);
                const parsedData = processData(res, data, opts);
                return parsedData instanceof Error
                  ? reject(parsedData)
                  : resolve(parsedData);
              });
          });

          req.on('error', error => {
            clearTimeout(timeout);
            reject(error);
          });

          if (method === Method.PUT || method === Method.POST) {
            req.write(processBody(opts, body));
          }
          req.end();
        })
        .catch(error => {
          clearTimeout(timeout);
          return reject(error);
        });
    } catch (error) {
      clearTimeout(timeout);
      return reject(error);
    }
  });
}
11748
function makeHttpRequest(encoding, next) {
  var start = Date.now();

  request(
    {
      url: 'http://localhost:1337/' + encoding,
      method: 'GET',
      headers: {
        'accept-encoding': encoding,
      },
    },
    function(err, data, body) {
      var time = Date.now() - start;

      console.log(encoding.toUpperCase() + ' COMPRESSION:');
      console.log('  status:', data.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        data.headers.should.not.have.property('content-encoding');
        body.should.equal('hello, ' + encoding);
      });

      console.log();

      next();
    }
  );
}
773029
function request( next ) {
	/* jshint validthis: true */
	var self = this,
		body = '',
		req;

	this.req.opts.agent = agent;

	// TODO: record request headers
	// TODO: record request header length
	// TODO: record request body length

	req = http.request( this.req.opts, onResponse );
	req.on( 'error', onError );

	this.start = Date.now();
	this.timer = process.hrtime();

	if ( this.req.body ) {
		req.write( this.req.body );
	}
	req.end();

	cache[ this.rid ] = req;

	/**
	* FUNCTION: onConnect( response, socket, head )
	*	Callback invoked upon connecting to a server.
	*
	* @private
	* @param {Object} response - HTTP response object
	* @param {Socket} socket - TCP socket
	* @param {Object} head - HTTP response head
	*/
	function onConnect( response, socket, head ) {
		// Do something...
	}

	/**
	* FUNCTION: onResponse( response )
	*	Callback invoked upon receiving an HTTP response.
	*
	* @private
	* @param {Object} response - HTTP response object
	*/
	function onResponse( res ) {
		self.res.status = res.statusCode;
		self.res.headers = res.headers;

		// TODO: record headers length

		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}

	/**
	* FUNCTION: onError( error )
	*	Callback invoked if an error is encountered while making a request.
	*
	* @private
	* @param {Error} error - error object
	*/
	function onError( error ) {
		self.req.error = error;
		if ( process.connected ) {
			// TODO: log (or not; serialize in output message?)
			console.error( process.pid, 'request', error );
		}
	}

	/**
	* FUNCTION: onData( chunk )
	*	Callback invoked after receiving a chunk of response data.
	*
	* @private
	* @param {Buffer} chunk - response data
	*/
	function onData( chunk ) {
		self.res.bytes += chunk.length;
		body += chunk.toString();
	}

	/**
	* FUNCTION: onEnd()
	*	Callback invoked after a response ends.
	*
	* @private
	*/
	function onEnd() {
		self.elapsed = process.hrtime( self.timer );
		self.end = Date.now();
		self.res.body = body;
		delete cache[ self.rid ];
		delete self.req.opts[ 'agent' ];
		next();
	}
}
773095
def request(self, command, message=None):
        
        if message is not None:
            message = Message.serialize(message)
        packet = Packet.request(command, message)
        response = self._communicate(packet)

        if response.response_type != Packet.CMD_RESPONSE:
            raise SessionException(
                "Unexpected response type {type}, "
                "expected '{response}' (CMD_RESPONSE)".format(
                    type=response.response_type,
                    response=Packet.CMD_RESPONSE
                )
            )

        return Message.deserialize(response.payload)