Stream the request to a socket
979077
def stream(socket)
      include_proxy_headers if using_proxy? && !@uri.https?
      Request::Writer.new(socket, body, headers, headline).stream
    end
435319
def send(self, data):
        
        sock = socket.socket(*self.sock_args)
        try:
            sock.connect(self.sock_addr)
        except socket.error as exc:
            raise socket.error("Can't connect to %r (%s)" % (self.url.geturl(), exc))

        try:
            # Send request
            sock.send(data)

            # Read response
            while True:
                chunk = sock.recv(self.CHUNK_SIZE)
                if chunk:
                    yield chunk
                else:
                    break
        finally:
            # Clean up
            sock.close()
442598
public void stream(String streamId, StreamCallback callback) {
    StdChannelListener listener = new StdChannelListener(streamId) {
      @Override
      void handleFailure(String errorMsg, Throwable cause) throws Exception {
        callback.onFailure(streamId, new IOException(errorMsg, cause));
      }
    };
    if (logger.isDebugEnabled()) {
      logger.debug("Sending stream request for {} to {}", streamId, getRemoteAddress(channel));
    }

    // Need to synchronize here so that the callback is added to the queue and the RPC is
    // written to the socket atomically, so that callbacks are called in the right order
    // when responses arrive.
    synchronized (this) {
      handler.addStreamCallback(streamId, callback);
      channel.writeAndFlush(new StreamRequest(streamId)).addListener(listener);
    }
  }
1103529
def __stream_request(self, method, url, request_args, headers=None):
        
        headers = headers if headers else {}
        response = self.__request(method, url, request_args,
                                  headers=headers, stream=True)
        lines = response.iter_lines(ITER_LINES_CHUNKSIZE)
        for line in lines:
            if line:
                data = json.loads(line.decode("utf-8"))
                yield data
781189
def request(url, message):
    """"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host, port = url.split(':')
    port = int(port)
    s.connect((host, port))
    s.send(pack(message))
    data = s.makefile().read()
    s.close()
    return data
148431
function () {
        var data = this._conn._data;
        if (data.length > 0 && !this._conn.paused) {
            for (var i = 0; i < data.length; i++) {
                if (data[i] !== null) {
                    var stanza, rawStanza;
                    if (data[i] === "restart") {
                        stanza = this._buildStream().tree();
                    } else {
                        stanza = data[i];
                    }
                    rawStanza = Strophe.serialize(stanza);
                    this._conn.xmlOutput(stanza);
                    this._conn.rawOutput(rawStanza);
                    this.socket.send(rawStanza);
                }
            }
            this._conn._data = [];
        }
    }
675127
function Client(rwStream, options)
{
	events.EventEmitter.call(this);
	
	var tidCounter = 0;
	var requestMap = {};
	var isClosed = true;
	var address = '';
	var host = '';
	
	var idlePingTimeout 	= getOption(options, 'idlePingTimeout',		0);
	var idleCloseTimeout	= getOption(options, 'idleCloseTimeout',	0);
	var autoRegister		= getOption(options, 'autoRegister', 		false);
	var logConnection		= getOption(options, 'logConnection', 		true);
	var autoResponseUnhandledCommand = getOption(options, 'autoResponseUnhandledCommand', true);
	
	this.isServer = options.isServer;
	
	function getAddress()
	{
		return util.format('%s:%s', rwStream.remoteAddress.replace(/^::ffff:/i, ''), rwStream.remotePort);		
	}
	
	function log(event)
	{
		if ( logConnection )
		{
			console.log(util.format('%s %s(%s)', event, host, address));
		}
	}
	
	this.closeStream = function() {

		//console.log('isClosed ' + isClosed);
		
		if ( !isClosed )
		{
			isClosed = true;
			
			log('CLOSE');
			
			if ( rwStream instanceof stream.Writable )
			{
				rwStream.end();
			}
		
			for ( var tid in requestMap )
			{
				if ( requestMap.hasOwnProperty(tid) )
				{
					clearTimeout(requestMap[tid].timer);
					requestMap[tid].callback({code: '500', tid: tid, args: ['socket_closed'], body: null, isValid: true});
					delete requestMap[tid];
				}
			}
			
			this.emit('close');
		}
	};
	
	if ( rwStream instanceof stream.Writable )
	{
		this.sendMessage = function(code, tid, args, body, callback) {
			var bodyBuf = Buffer.isBuffer(body) ? body : 
				typeof(body) === 'string' ? Buffer.from(body) : 
					null;
			tid = tid === -1 ? ++tidCounter : tid;
			tid = '' + tid;
			var bodyLen = bodyBuf ? bodyBuf.length : 0;
			var header = util.format('%s %s %d%s\r\n', code, tid, bodyLen, encodeArgs(args));
			var headerLen = Buffer.byteLength(header);
			var msg = {code: code, tid: tid, args: args, body: body};
			if ( options.debugHeader )
			{
				console.log("send msg: %s", msg2str(msg));
			}
			rwStream.write(header, callback);
			if ( bodyLen > 0 )
			{
				rwStream.write(bodyBuf);
			}
		};

		this.sendRequest = function(code, args, body, timeout, callback) {
			var tid = ++tidCounter;
			this.sendMessage(code, tid, args, body);
			requestMap[tid] = {
				callback: callback,
				timer: setTimeout(() => this.emit('message_timeout', tid), timeout)
			};
		};
	}
	
	if ( rwStream instanceof stream.Readable )
	{
		var parser = textParser.createParser((msg) => {

			if ( options.debugHeader )
			{
				console.log("recv msg: %s", msg2str(msg));
			}

			if ( !msg.isValid && this.sendMessage )
			{
				this.sendMessage('201', 0, 'invalid_command');
			}
			else
			{
				if ( /^\d+$/.test(msg.code) )
				{
					var tid = msg.tid !== null && /^\d+$/.test(msg.tid) ? msg.tid * 1 : 0;
					
					if ( tid > 0 )
					{
						if ( requestMap.hasOwnProperty(msg.tid) )
						{
							clearTimeout(requestMap[msg.tid].timer);
							requestMap[msg.tid].callback(msg);
							delete requestMap[msg.tid];
						}
						else
						{
							console.log(util.format('ERR dangling response: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
						}
					}
					else
					{
						console.log(util.format('ERR invalid tid: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
					}
				}
				else
				{
					var isHandled = false;
					
					if ( this.listenerCount(msg.code) > 0 )
					{
						isHandled = true;
						this.emit(msg.code, msg);
					}
					
					if ( this.listenerCount('message') > 0 )
					{
						isHandled = true;
						this.emit('message', msg);
					} 
					
					if ( !isHandled && autoResponseUnhandledCommand && this.sendMessage )
					{
						this.sendMessage('201', msg.tid, 'unknown_command');
					}
				}
			}
		});
		
		rwStream.on('data', (data) => {
			parser.feed(data);
		});
		
		rwStream.on('end', (e) => {
			this.closeStream();
		});
	}
	
	if ( rwStream instanceof net.Socket )
	{
		if ( !rwStream.connecting )
		{
			this.address = address = getAddress();
			isClosed = false;
			log('ACCEPT');
		}

		if ( idlePingTimeout > 0 )
		{
			rwStream.setTimeout(idlePingTimeout);
		}
		else if ( idleCloseTimeout > 0 )
		{
			rwStream.setTimeout(idleCloseTimeout);
		}
		
		rwStream.on('timeout', () => {
			if ( idlePingTimeout > 0 )
			{
				this.sendMessage('PING', 0, [], null);
				log('PING');
			}
			else if ( idleCloseTimeout > 0 )
			{
				this.closeStream();
			}
			else
			{
				this.emit('timeout');
			}
		});
		
		rwStream.on('connect', () => {
			this.address = address = getAddress();
			isClosed = false;
			log('CONNECT');
			if ( autoRegister )
			{
				this.sendMessage('RGST', 0, os.hostname());
				log('RGST');
			}
			this.emit('connect');
		});
		
		rwStream.on('close', (had_error) => {
			this.closeStream();
		});
		
		this._getSessionManager = function() {
			if ( !this.sessionManager )
			{
				this.sessionManager = new SessionManager(this, options);
			}
			return this.sessionManager;
		};
		
		this.onSession = function(protocol, callback) {
			var smgr = this._getSessionManager();
			var listener_options = Object.assign({}, options, {protocol: protocol});
			var slnr = new SessionListener(listener_options);
			slnr.on('session', callback);
			smgr.registerListener(slnr);
		};
		
		this.createSession = function(protocol, session_args) {
			var smgr = this._getSessionManager();
			var session_options = Object.assign({}, options, {protocol: protocol, session_args: session_args});
			return smgr.createSession(session_options);
		};
	} 
	
	rwStream.on('error', (e) => {
		log('ERROR ' + e.message);
		this.closeStream();
		this.emit('error', e);
	});
	
	this.on('message_timeout', (tid) => {
		if ( requestMap.hasOwnProperty(tid) )
		{
			requestMap[tid].callback({code: '500', tid: tid, args:['message_timeout'], body: null, isValid: true});
			delete requestMap[tid];
		}
	});
	
	this.on('RGST', (msg) => {
		host = msg.args.length > 0 ? msg.args[0] : '';
		log('RGST');
	});
	
	this.on('PING', (msg) => {
		log('PING');
	});
}
874490
function startStream () {
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', function(data) {
    return {
      "--parse"     : function (string) {
        var result = parse(string)
        process.stdout.write(JSON.stringify(result, null, 2))
      },
      "--serialize" : function (string) {
        var result = serialize(JSON.parse(string))
        process.stdout.write(result)
      }
    }[$mode](data)
  })
}
479205
def handle_client_stream(self, stream, is_unix=False):
        

        assert stream
        data = []
        stream.settimeout(2)
        while True:
            try:
                if is_unix:
                    buf = stream.recv(1024)
                else:
                    buf = stream.read(1024)
                if not buf:
                    break
                data.append(buf)
            except (AttributeError, ValueError) as message:
                logger.error(message)
                return
            except (ssl.SSLError) as exception:
                logger.debug('Error: %s', exception[0])
                break
            except (socket.timeout) as exception:
                logger.debug('Error: %s', exception)
                break
        data = b''.join(data)
        if len(data) <= 0:
            logger.debug("Empty client stream")
            return
        try:
            response = self.handle_command(data)
        except OSPDError as exception:
            response = exception.as_xml()
            logger.debug('Command error: %s', exception.message)
        except Exception:
            logger.exception('While handling client command:')
            exception = OSPDError('Fatal error', 'error')
            response = exception.as_xml()
        if is_unix:
            send_method = stream.send
        else:
            send_method = stream.write
        self.write_to_stream(send_method, response)
1360723
@Override
  public StreamImpl stream()
    throws IOException
  {
    if (_streamImpl == null) {
      _streamImpl = new SocketStream();
    }

    _streamImpl.init(_s);

    return _streamImpl;
  }
1275939
def _create_sending_stream(self, pub_addr):
        
        sock = self._zmq_context.socket(zmq.PUB)
        sock.setsockopt(zmq.IDENTITY, self.sender_id)
        sock.connect(pub_addr)
        stream = ZMQStream(sock, io_loop=self.io_loop)

        return stream
427987
def send_recv( request )
      connection.write( request.to_protocol )
      line = connection.readline
      resp = KJess::Response.parse( line )
      resp.read_more( connection )
      raise resp if resp.error?
      return resp
    end
37356
def post(uri, body, opts = {}, &block)
      initialize_socket(uri, opts)
      HttpStream::post(uri, body, opts, &block)
    rescue IOError => e
      raise e unless @intentional_termination
    end
239797
def _socket_connect(self):
        """"""
        self.usage_count = 0
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            s.connect((self._host, self._port))
            self.__stream = self.__backend.register_stream(s, **self.__kwargs)
            self.__stream.set_close_callback(self._socket_close)
            self.__alive = True
        except socket.error, error:
            raise InterfaceError(error)
498461
def receive(self):
        
        try:
            itr = 0
            while self.connected:
                
                r, w, e = select.select(
                    (self.sock, ), (), (), 10.0)
                
                if r:
                    message = json.loads(self.recv())
                    
                    if 'fetch' in message:
                        self.fetch_id = message['fetch']
                    
                    if 'failure' in message:
                        raise InvalidFetch(message['failure'])
                    
                    if 'records' in message:
                        if 'added' in message['records']:
                            num = len(message['records']['added'])
                        else:
                            num = len(message['records'])
                        
                        logger.debug('Query returned %s records.', num)
                        if self.max_recv:
                            itr += 1
                        
                    if 'end' in message:
                        logger.debug('Received end message: %s' % message['end'])
                        yield message
                        break
                    
                    yield message
                    if self.max_recv and self.max_recv <= itr:
                        break   

        except (Exception, KeyboardInterrupt, SystemExit, FetchAborted) as e:
            logger.info('Caught exception in receive: %s -> %s', type(e), str(e))
            if isinstance(e, (SystemExit, InvalidFetch)):
                # propagate SystemExit, InvalidFetch
                raise
        finally:
            if self.connected:
                if self.fetch_id:
                    self.send(json.dumps({'abort': self.fetch_id}))
                self.close()
            
            if self.thread:
                self.event.set()
                while self.thread.isAlive():
                    self.event.wait(1)
            
            logger.info('Closed web socket connection normally.')
952537
def __call_stream(self, uri, params=None, method="get"):
        
        try:
            resp = self.__get_response(uri, params, method, True)
            assert resp.ok
        except AssertionError:
            raise BadRequest(resp.status_code)
        except Exception as e:
            log.error("Bad response: {}".format(e), exc_info=True)
        else:
            return resp
418597
def communicate(self):
        """"""
        request_seen = False
        try:
            while True:
                # (re)set req to None so that if something goes wrong in
                # the RequestHandlerClass constructor, the error doesn't
                # get written to the previous request.
                req = None
                req = self.RequestHandlerClass(self.server, self)
                
                # This order of operations should guarantee correct pipelining.
                req.parse_request()
                if not req.ready:
                    # Something went wrong in the parsing (and the server has
                    # probably already made a simple_response). Return and
                    # let the conn close.
                    return
                
                request_seen = True
                req.respond()
                if req.close_connection:
                    return
        except socket.error, e:
            errnum = e.args[0]
            # sadly SSL sockets return a different (longer) time out string
            if errnum == 'timed out' or errnum == 'The read operation timed out':
                # Don't error if we're between requests; only error
                # if 1) no request has been started at all, or 2) we're
                # in the middle of a request.
                # See http://www.cherrypy.org/ticket/853
                if (not request_seen) or (req and req.started_request):
                    # Don't bother writing the 408 if the response
                    # has already started being written.
                    if req and not req.sent_headers:
                        try:
                            req.simple_response("408 Request Timeout")
                        except FatalSSLAlert:
                            # Close the connection.
                            return
            elif errnum not in socket_errors_to_ignore:
                if req and not req.sent_headers:
                    try:
                        req.simple_response("500 Internal Server Error",
                                            format_exc())
                    except FatalSSLAlert:
                        # Close the connection.
                        return
            return
        except (KeyboardInterrupt, SystemExit):
            raise
        except FatalSSLAlert:
            # Close the connection.
            return
        except NoSSLError:
            if req and not req.sent_headers:
                # Unwrap our wfile
                self.wfile = CP_fileobject(self.socket._sock, "wb", self.wbufsize)
                req.simple_response("400 Bad Request",
                    "The client sent a plain HTTP request, but "
                    "this server only speaks HTTPS on this port.")
                self.linger = True
        except Exception:
            if req and not req.sent_headers:
                try:
                    req.simple_response("500 Internal Server Error", format_exc())
                except FatalSSLAlert:
                    # Close the connection.
                    return