Ejemplo n.º 1
0
int main(int argc, const char *argv[])
{
    fd_set allreads;
    fd_set readmask;

    int socket = 0;
    int rc = 0;
    RingBuffer *in_rb = RingBuffer_create(1024 * 10);
    RingBuffer *sock_rb = RingBuffer_create(1024 * 10);

    check(argc == 3, "USAGE: netclient HOST PORT");

    socket = client_connect(argv[1], argv[2]);
    check(socket >= 0, "Connect to %s:%s failed.", argv[1], argv[2]);

    FD_ZERO(&allreads);
    FD_SET(socket, &allreads);
    FD_SET(0, &allreads);

    while(1) {
        readmask = allreads;
        rc = select(socket + 1, &readmask, NULL, NULL, NULL);
        check(rc >= 0, "Select failed");

        if(FD_ISSET(0, &readmask)) {
            rc = read_some(in_rb, 0, 0);
            check_debug(rc != -1, "failed to read from stdin.");
        }

        if(FD_ISSET(socket, &readmask)) {
            rc = read_some(sock_rb, socket, 0);
            check_debug(rc != -1, "failed to read from socket.");
        }

        while(!RingBuffer_empty(sock_rb)) {
            rc = write_some(sock_rb, 1, 0);
            check_debug(rc != -1, "failed to write to stdout.");
        }

        while(!RingBuffer_empty(in_rb)) {
            rc = write_some(in_rb, socket, 1);
            check_debug(rc != -1, "failed to write to socket.");
        }

    }

    RingBuffer_destroy(in_rb);
    RingBuffer_destroy(sock_rb);

    return 0;

error:
    return -1;
}
Ejemplo n.º 2
0
static void read_test(void *v_t)
{
	struct read_test *t = v_t;
	enum stream_result sres;
	ssize_t res;

	switch (t->step) {
	case 0:
		t->stream = delim_read_next(t->dr);
		t->pos = 0;

	STEP:
		res = read_some(t, 8);
		if (res == STREAM_WAITING)
			return;

		assert(res == 7);
		assert(!memcmp(t->buf, "hello, ", 7));

	STEP:
		sres = stream_close(t->stream, &t->tasklet, &t->err);
		if (sres == STREAM_WAITING)
			return;

		assert(sres == STREAM_OK);
		stream_destroy(t->stream);
		t->stream = delim_read_next(t->dr);
		t->pos = 0;

	STEP:
		res = read_some(t, 7);
		if (res == STREAM_WAITING)
			return;

		assert(res == 6);
		assert(!memcmp(t->buf, "world!", 6));

	STEP:
		sres = stream_close(t->stream, &t->tasklet, &t->err);
		if (sres == STREAM_WAITING)
			return;

		assert(sres == STREAM_OK);
		stream_destroy(t->stream);
	}

	tasklet_stop(&t->tasklet);
	application_stop();
}
Ejemplo n.º 3
0
bool async_file::open(int fd, OpenMode mode)
{
    logger::debug() << "Open fd " << fd << " mode " << mode;
    assert(mode & ReadWrite);

    if (sd.is_open()) {
        set_error("async_file already open");
        logger::debug() << error_string();
        return false;
    }

    sd.assign(::dup(fd));

    // Place the file descriptor in nonblocking mode
    sd.non_blocking(true);

    mode_ = mode;

    if (mode & Read) {
        boost::system::error_code ec;
        read_some(ec, 0);
    }
    if (mode & Write) {
    //     snout = new QSocketNotifier(fd, QSocketNotifier::Write, this);
    //     connect(snout, SIGNAL(activated(int)),
    //         this, SLOT(readyWrite()));
    }

    return true;
}
Ejemplo n.º 4
0
 size_t read_some( AsyncReadStream& s, boost::asio::streambuf& buf )
 {
     char buffer[1024];
     size_t bytes_read = read_some( s, boost::asio::buffer( buffer, sizeof(buffer) ) );
     buf.sputn( buffer, bytes_read );
     return bytes_read;
 }
Ejemplo n.º 5
0
Udp::Udp(
      const char *ipAddress,
      const char *pRemPort,
      const char *pLocPort,
      boost::lockfree::queue<MsgData_t> *pQueue
)  : m_pQueue(NULL),
     m_io(),
     m_socket( m_io ),
     m_rem_endpoint(boost::asio::ip::address::from_string(ipAddress), atoi(pRemPort)),
     m_loc_endpoint(boost::asio::ip::udp::v4(), atoi(pLocPort))

{
   boost::system::error_code myError;

   m_socket.open( boost::asio::ip::udp::v4(), myError);
   if (myError) {
      std::cout << "Open - " << myError.message() << std::endl;
      exit(1);
   }

   m_socket.bind( m_loc_endpoint, myError );
   if (myError) {
      std::cout << "Bind - " << myError.message() << std::endl;
      exit(1);
   }

   this->m_pQueue = pQueue;                  /* Set the pointer to the queue */

   read_some();

   // run the IO service as a separate thread, so the main thread can do others
   boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io));
}
Ejemplo n.º 6
0
void Udp::read_handler(
      const boost::system::error_code& error,
      size_t bytes_transferred
)
{
   if ( !error ) {                             /* Data received with no error */

      /* Construct a new msg event indicating that a msg has been received */
      MsgData_t msg;
      memset(&msg, 0, sizeof(msg));
      msg.src = _DC3_EthCli;
      msg.dst = _DC3_EthCli;
      msg.dataLen = bytes_transferred;
      memcpy( msg.dataBuf, read_msg_, msg.dataLen );

      /* Put the data into the queue for ClientApi to read */
      if(!this->m_pQueue->push(msg)) {
         ERR_printf( m_pLog, "Unable to push data into queue.");
      }
   } else {
      ERR_printf(this->m_pLog, "Unable to read UDP data");
   }

   read_some();                                           /* Continue reading */
}
std::size_t file_handle::read_some(const MutableBufferSequence& buffers)
{
  error_code ec;
  std::size_t s = read_some(buffers, ec);
  detail::throw_error(ec);
  return s;
}
 void async_read_some(const MutableBufferSequence& buffers, Handler handler)
 {
   boost::system::error_code ec;
   std::size_t bytes_transferred = read_some(buffers, ec);
   io_service_.post(boost::asio::detail::bind_handler(
         handler, ec, bytes_transferred));
 }
Ejemplo n.º 9
0
 std::size_t read_some(const MutableBufferSequence& buffers)
 {
   boost::system::error_code ec;
   std::size_t bytes_read = read_some(buffers, ec);
   detail::throw_error(ec);
   return bytes_read;
 }
Ejemplo n.º 10
0
	void tryHttpRequest() {
		try {
			HttpRequestPtr request(new HttpRequest(work_in_progress_));
			// TODO: buffer_ may contain multiple requests at the same time
			// HttpRequest() should take one off of it and return the length read
			work_in_progress_.clear();
			HttpResponsePtr response = request_exception_wrapper(request, delegate_);
			respond(response);
			read_some();
		} catch(HttpMessage::IncompleteHttpMessageException &) {
			read_some();
		} catch(HttpRequest::InvalidHttpMessageException &e) {
			std::cerr << "Parse Error: " << e.what() << std::endl;
			// TODO: send back Bad Request and close the connection
		}
	}
Ejemplo n.º 11
0
size_t stream_socket::read_some(mutable_buffer const &buffer)
{
	system::error_code e;
	size_t r=read_some(buffer,e);
	if(e)
		throw system::system_error(e);
	return r;
}
Ejemplo n.º 12
0
events::events(io::io_service &service, events::callback _callback)
    : on_ready(std::move(_callback)),fd(createfd(true)),
      ioEntry(service, fd, EPOLLIN, [this](uint32_t)
      {
          uint64_t res;
          read_some(fd, &res, sizeof(res));
          this->on_ready(res);
      })
{
}
Ejemplo n.º 13
0
 std::size_t read_some(const MutableBufferSequence& buffers)
 {
   asio::error_code ec;
   std::size_t bytes_transferred = read_some(buffers, ec);
   if (ec)
   {
     asio::system_error ex(ec);
    // boost::throw_exception(ex);
   }
   return bytes_transferred;
 }
Ejemplo n.º 14
0
 std::size_t read_some(const MutableBufferSequence& buffers)
 {
   asio::error_code ec;
   std::size_t bytes_transferred = read_some(buffers, ec);
   if (ec)
   {
     std::system_error ex(ec);
     throw ex;
   }
   return bytes_transferred;
 }
Ejemplo n.º 15
0
size_t tcp_stream::read_explicit(io::buffer buffer, const size_t bytes_requested)
{
    size_t bytes_transferred = 0;
    while (bytes_transferred < bytes_requested)
    {
        bytes_transferred += read_some(buffer, bytes_requested);
        buffer.ptr += bytes_transferred;
        buffer.capacity -= bytes_transferred;
    }
    return bytes_transferred;
}
Ejemplo n.º 16
0
size_t stream_socket::read(mutable_buffer const &buffer,system::error_code &e)
{
	mutable_buffer tmp = buffer;
	size_t count = 0;
	while(!tmp.empty()) {
		size_t n = read_some(tmp,e);
		count+=n;
		if(e) return count;
		tmp+=n;
	}
	return count;
}
Ejemplo n.º 17
0
int
main(void)
{ 
  char buf[20];
  while (3==read_some(buf,3,'\n',0))
   { buf[3] = 0;
     if (strcmp(buf,"DEF") ==0)
       { printf("\n%s",buf);
	 while(1==read_some(buf,1,'\"',1))
	   { if (buf[0] == ')')
		 break;
	       }}
     if (strcmp(buf,"DO_") ==0)
       {printf("\n%s",buf);
	read_some(buf,0,'\n',1);
	ungetc('\n',stdin);
      }
   }
  printf("\n");
  exit(0);
  
}
Ejemplo n.º 18
0
void async_file::write_some(
    boost::system::error_code const& error, // Result of operation.
    std::size_t bytes_transferred)          // Number of bytes read.
{
    if (bytes_transferred > 0)
        on_bytes_written(bytes_transferred);

    inq.emplace_back(256);
    sd.async_write_some(
        boost::asio::buffer(inq.back().as_vector()),
        [this](boost::system::error_code const& error, std::size_t bytes_transferred) {
            read_some(error, bytes_transferred);
        });
}
Ejemplo n.º 19
0
// Load data from the file.
bool JsonLoader::Reader::read_some() {
    if (_fd < 0) {  // loading from a string.
        return false;
    }
    ssize_t nr = _file_buf.append_from_file_descriptor(_fd, 65536);
    if (nr < 0) {
        if (errno == EINTR) {
            return read_some();
        }
        PLOG(ERROR) << "Fail to read fd=" << _fd;
        return false;
    } else if (nr == 0) {
        return false;
    } else {
        return true;
    }
}
Ejemplo n.º 20
0
void stream_socket::async_read_some(mutable_buffer const &buffer,io_handler const &h)
{
	if(!dont_block(h))
		return;
	#ifdef BOOSTER_AIO_FORCE_POLL
	reader_some::pointer reader(new reader_some(h,buffer,this));
	on_readable(reader);
	#else
	system::error_code e;
	size_t n = read_some(buffer,e);
	if(e &&  would_block(e)) {
		reader_some::pointer reader(new reader_some(h,buffer,this));
		on_readable(reader);
	}
	else {
		io_binder::pointer binder(new io_binder( h,n,e ));
		get_io_service().post(binder);
	}
	#endif
}
Ejemplo n.º 21
0
 std::size_t read_some(const MutableBufferSequence& buffers
                      , boost::system::error_code& ec)
 {
   ec = boost::system::error_code();
   typename MutableBufferSequence::const_iterator iter = buffers.begin();
   typename MutableBufferSequence::const_iterator end = buffers.end();
   DWORD i = 0;
   size_t buffer_size = 0;
   size_t bytes_transferred = 0;
   size_t total_bytes_transferred = 0;
   for (; !ec && iter != end && i < max_buffers; ++iter, ++i)
   {
     boost::asio::mutable_buffer buffer(*iter);
     buffer_size = boost::asio::buffer_size(buffer);
     bytes_transferred = read_some(
       boost::asio::buffer_cast<char*>(buffer), buffer_size , ec);
     if (bytes_transferred < buffer_size)
       return bytes_transferred;
     total_bytes_transferred += buffer_size;
   }
   return total_bytes_transferred;
 }
Ejemplo n.º 22
0
// Separate jsons with closed braces.
bool JsonLoader::Reader::get_next_json(butil::IOBuf* json1) {
    if (_file_buf.empty()) {
        if (!read_some()) {
            return false;
        }
    }
    json1->clear();
    while (1) {
        butil::IOBufAsZeroCopyInputStream it(_file_buf);
        const void* data = NULL;
        int size = 0;
        int total_size = 0;
        int skipped = 0;
        for (; it.Next(&data, &size); total_size += size) {
            for (int i = 0; i < size; ++i) {
                const char c = ((const char*)data)[i];
                if (_brace_depth == 0) {
                    // skip any character until the first left brace is found.
                    if (c != '{') {
                        ++skipped;
                        continue;
                    }
                }
                switch (c) {
                case '{':
                    if (!_quoted) {
                        ++_brace_depth;
                    } else {
                        VLOG(1) << "Quoted left brace";
                    }                        
                    break;
                case '}':
                    if (!_quoted) {
                        --_brace_depth;
                        if (_brace_depth == 0) {
                            // the braces are closed, a complete object.
                            _file_buf.cutn(json1, total_size + i + 1);
                            json1->pop_front(skipped);
                            return possibly_valid_json(*json1);
                        } else if (_brace_depth < 0) {
                            LOG(ERROR) << "More right braces than left braces";
                            return false;
                        }
                    } else {
                        VLOG(1) << "Quoted right brace";
                    }
                    break;
                case '"':
                    if (_quoted) {
                        if (_quote_char == '"') {
                            _quoted = false;
                        }
                    } else {
                        _quoted = true;
                        _quote_char = '"';
                    }
                    break;
                case '\'':
                    if (_quoted) {
                        if (_quote_char == '\'') {
                            _quoted = false;
                        }
                    } else {
                        _quoted = true;
                        _quote_char = '\'';
                    }
                    break;
                default:
                    break;
                    // just skip
                }
            }
        }
        if (!_file_buf.empty()) {
            json1->append(_file_buf);
            _file_buf.clear();
        }
        if (!read_some()) {
            json1->pop_front(skipped);
            if (!json1->empty()) {
                return possibly_valid_json(*json1);
            }
            return false;
        }
    }
    return false;
}
Ejemplo n.º 23
0
		void bind(endpoint_type const& endpoint);
		std::size_t available() const;
#endif

		void open(protocol_type const& p, error_code& ec);
		void close(error_code& ec);
		endpoint_type local_endpoint(error_code& ec) const;
		endpoint_type remote_endpoint(error_code& ec) const;
		void bind(endpoint_type const& endpoint, error_code& ec);
		std::size_t available(error_code& ec) const;
		int type() const;


		template <class Mutable_Buffers>
		std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)
		{ TORRENT_SOCKTYPE_FORWARD_RET(read_some(buffers, ec), 0) }

		template <class Mutable_Buffers, class Handler>
		void async_read_some(Mutable_Buffers const& buffers, Handler const& handler)
		{ TORRENT_SOCKTYPE_FORWARD(async_read_some(buffers, handler)) }

		template <class Const_Buffers>
		std::size_t write_some(Const_Buffers const& buffers, error_code& ec)
		{ TORRENT_SOCKTYPE_FORWARD_RET(write_some(buffers, ec), 0) }

		template <class Const_Buffers, class Handler>
		void async_write_some(Const_Buffers const& buffers, Handler const& handler)
		{ TORRENT_SOCKTYPE_FORWARD(async_write_some(buffers, handler)) }

		template <class Handler>
		void async_connect(endpoint_type const& endpoint, Handler const& handler)
Ejemplo n.º 24
0
	void start() {
		auto that = shared_from_this();
		socket_->async_start(
			[that]() { that->read_some(); }
		);
	}